FP looks at things as "What to do?" rather than "How to do it?"
// imperative way of doing things
const findMean = (...numbers) => {
let x = 0;
numbers.forEach((number) => {
x += number;
});
const numberOfNumbers = numbers.length;
return x / numberOfNumbers;
};
// declarative way of doing things
const sum = (numbers) => numbers.reduce((acc, n) => n + acc, 0);
const findMeanFp = (...numbers) => sum(numbers) / numbers.length;
- Immutability
- Separating functions and data
- First-class functions
Currying allows to create custom functions
const add = (x, y, z) => x + y + z;
console.log(add(1,2,3) // 6
// Lets say we want y and z to be fixed
const addCurry1 = x => (y, z) => x + y + z;
console.log(addCurry1(1)(2,3)) // 6
// Now we can create several add(ers) which would need to be called with two more arguments
const add1 = addCurry1(1) // 1 is already curried-in
console.log(add1(2,3)) // 6
const add2 = addCurry(2) // 2 is already curried-in
console.log(add2(1,3)) // 6
// we can also have another variant
const addCurry2 = (x, y) => z => x + y + z
console.log(addCurry2(1, 2)(3))//6
// Now we can create adders which would require to be called with one more argument
const add1and2 = addCurry2(1, 2)
console.log(add1and2(3)) // 6
const add2and3 = addCurry2(2, 3);
console.log(add2and3(1)) // 6