[ES6] Functional Programming: cheatsheet
This is a slowly growing note, content is updated whenever better and easier syntax is discovered.
Content:
1- *High order function
2- Update Object
3- Update Array
4- Alternate two value
5- *Filter and Find
6- Reduce
7- Some
8- Sort
9- *Chain Promise
10- Object.entries (enumerating [key, val] of Obj)
11- [new Set([1,1,2 ])] Get all unique values
12- Conditionally adding keys to objects
1- High order function
const add = x => y => y + x;
//add(2)(3)
//5
or
const isNumber = n => x => x === n
const arr = ['1','2','3']arr.filter( isNumber("3") )
//["3"]
2- Update object
var state = {
id: 1,
points: 100,
name: "Goran"
};
var newState = {
...state,
points: 120
}
/*
{
id: 1,
points: 120,
name: "Goran"
}
*/
3- Update array
var state = [1,1,1,1];
// state[2]++ // [1,1,2,1]
var index = 2;
var newState = [
...state.slice(0, index),
state[index] + 1,
...state.slice(index + 1)
];
console.log(newState);
/*
[1,1,2,1]
*/
4- Alternate two value
spread operation
var a = 1, b = 2;[a , b] = [b , a]// a=2, b=1
5- Filter, Find
Filter
returns the new array of the elements in the array that satisfies the provided testing function.
function isBigEnough(element) {
return element >= 15;
}
[12, 5, 8, 130, 150].filter(isBigEnough); // [130, 150]
Find
returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined
is returned.
function isBigEnough(element) {
return element >= 15;
}
[12, 5, 8, 130, 150].find(isBigEnough); // 130
6- Reduce
sum of all elements of an array
var arr = [0, 1, 2, 3, 4]arr.reduce( (prev, curr) => prev + curr )
//10arr.reduce( (prev, curr) => prev + curr , 20)
//30
7- Some
[2, 5, 8, 1, 4].some(x => x > 10); // false
[12, 5, 8, 1, 4].some(x => x > 10); // true
8- Sort
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
9- Chain Promise
Taken the value from resolve as the parameter of next promise
//resolve square of input
var square = function(para) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('para: ', para)
resolve(para * para)
}, 1000)
})
}square(2)
.then(square)
.then(square)// para: 2
// para: 4
// para: 16
10- Object.entries (enumerating [key, val] of Obj)
Enumerating property [key, value]
pairs of an Object
const a = {id: "mockId", name: "peter"}Object.entries(obj).map(([key, value]) =>
console.log(`${key} : ${value}`)
)// id : mockId
// name : peter
11- [new Set([1,1,2 ])] Get all unique values
ES6 has a native object Set
to store unique values. To get an array with unique values you could do now this:
const myArray = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(myArray)];
// unique is ['a', 1, 2, '1']
12- Conditionally adding keys to objects
const buildAnObjectFromAQuery = query => ({
...query.foo && { foo: query.foo },
...query.bar && { bar: query.bar },
});
React
Below is some note about writing React in a functional way, which is collected in my daily work:
Props Default to “True”
<MyTextBox autocomplete />
as same as
<MyTextBox autocomplete={true} />
Spread Attributes
use ...
as a "spread" operator to pass the whole props object
function App1() {
return <Greeting firstName="Ben" lastName="Hector" />;
}function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return <Greeting {...props} />;
}
You might be interested
JavaScript is not a functional programming language but we can still apply some functional principles to our code. We’ll look at a number of patterns in the functional space (by Dan Mantyla):
- Function passing
- Filters and pipes
- Accumulators
- Memoization
- Immutability
- Lazy instantiation
Characteristics of Functional Programming :
- side-effect-free
- making code more maintainable
- separating GET and SET functions
- same inputs and the result will be the same
Terminology:
— Higher order functions : takes a function as a parameter, or returns a function as its result.
— First order : it treats functions like expressions of any other type. Functions are like any other object.
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
https://gist.github.com/gorangajic/e902c2ee994260b3348d
https://www.safaribooksonline.com/library/view/javascript-functional-programming/9781787124660/
https://facebook.github.io/react/docs/jsx-in-depth.html
https://developer.ibm.com/node/2016/01/11/higher-order-functions-in-es6easy-as-a-b-c/