const hourlyVisits = [100, 200, 300];
function visitDiffFromAvg(visits) {
const sum = visits.reduce((t, h) => t + h);
const hours = visits.length;
const latest = visits.pop();
return latest - (sum / hours);
};
// elsewhere...
const diffFromDailyAvg = visitDiffFromAvg(hourlyVisits);
const dailyPeakVisits = Math.max(...hourlyVisits); // 200
import moment from 'moment';
function getTodaysVisits(visits) {
const today = moment().format('YYYY-MM-DD');
return visits[today];
}
A pure function can be replaced by the value it returns.
function cleanResponseKeys(response) {
const keys = Object.keys(response);
process(response);
return keys.filter(item => name !== 'Matt');
}
Some array methods can cause unexpected side-effects if you don't know that they modify the array in place.
const x = [1, 2, 3];
const y = x.push(1);
console.log(x); // [1, 2, 3, 1]
const z = x.sort();
console.log(x); // [1, 1, 2, 3]
Mutator Methods | Pure Methods |
---|---|
pop | concat |
push | includes |
reverse | join |
shift | slice |
sort | map |
splice | filter |
unshift | reduce |
import moment from 'moment';
const today = moment(), visits = {...};
function getYearAgoVisits(visits, date) {
const yearAgo = date.subtract(1, 'year');
return visits[yearAgo];
}
getYearAgoVisits(visits, today);
const personalInfo = {
name: 'Matt',
town: 'Burlington',
age: 29
};
const olderMatt = Object.assign(
{},
personalInfo,
{ age: 30 }
);
A little syntactic sugar on top of Object.assign()
const olderMatt = {
...personalInfo,
age: 30
};
// where do people look up what stage features are in?
Part of ES2017
const x = Object.freeze({ a: 1, b: 2 });
x.a = 5;
console.log(x); // { a: 1, b: 2}
const y = Object.freeze({ a: 1, b: 2, c: [1, 2, 3]})
y.c[0] = 5;
console.log(y); // { a: 1, b: 2, c: [5, 2, 3]}
const x = [1, 2, 3];
const x = Immutable.List([1, 2, 3])
shouldComponentUpdate(nextProps) {
return this.props !== nextProps;
}