* Array functions
find, filter, map, reduce, every, some
let meetups = [
{name: 'js', isActive: true, members: 450},
{name: 'Angular', isActive: true, members: 900},
{name: 'Node', isActive: false, members: 900}
];
// filter
let activeMeetupsFP = meetups.filter((m) => {return m.isActive});
console.log(activeMeetupsFP);
// [{"name":"js","isActive":true,"members":450},
// {"name":"Angular","isActive":true,"members":900}]
// find
let js = meetups.find((m) => {
return m.name === 'js';
});
console.log(js);
// map, reduce
let sumFPChain = meetups.filter((m) => {
return m.isActive;
}).map((m)=> {
return m.members - 0.1 * m.members;
}).reduce((acc, m) => {
return acc + m;
}, 0);
console.log(sumFPChain); // 1215
Libraries to support FP
RamdaJS, UnderscoreJS, lodash
* First Class Functions
var isActive = (meetup) => {
return meetup.isActive;
}
meetups.filter(isActive);
* Currying
Currying is the technique of
translating the evaluation of a function that
takes multiple arguments into evaluating a sequence of functions,
each with a single argument.
let byName = (name) => {
return (meetup) => {
return meetup.name === name
}
}
meetups.find(byName('js'))
* Function Composition
let byName = (name) => {
return (meetup) => {
return meetup.name === name
}
}
let isValid = isFinite(meetups.find(byName('js')).members)
* Side Effects
const scheduleMeetup = (date, place) => {
meetup.date = date;
meetup.place = place;
if (meetup.members < 5) {
meetup.isActive = false;
}
}
const publishMeetup = () => {
if (meetup.isActive)
meetup.publish = true;
}
* Immutability
change the original data / return a new copy of the data ?
Immutable Library
Seamless-immutable, ImmutableJS
reduce方法用法示例:
Grouping objects by a property:
var people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
Bonding arrays contained in an array of objects using the spread operator and initialValue
// friends - an array of objects
// where object field "books" - list of favorite books
var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(function(accumulator, currentValue) {
return [...accumulator, ...currentValue.books];
}, ['Alphabet']);
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]