`new Map()` const map1 = Immutable.Map([ ['one', 1], ['two', 2], ['three', 3] ]); const map2 = map1.set('four', 4); console.log([...map1]); // [['one', 1], ['two', 2], ['three', 3]] console.log([...map2]); // [['one', 1], ['two', 2], ['three', 3], ['four', 4]] // Use in place of `new Set()` const set1 = Immutable.Set([1, 2, 3, 3, 3, 3, 3, 4]); const set2 = set1.add(5); console.log([...set1]); // [1, 2, 3, 4] console.log([...set2]); // [1, 2, 3, 4, 5] 函数组合
记不记得在中学时我们学过一些像 (f ° g)(x) 的器械?你那时可能想,“我什么时刻会用到这些?”,好了,如今就用到了。你预备好了吗?f ° g读作 “函数 f 和函数 g 组合”。对它的懂得有两种等价的方法,如等式所示: (f ° g)(x) = f(g(x))。你可以认为 f ° g 是一个零丁的函数,或者视作将调用函数 g 的结不雅作为参数传给函数 f。留意这些函数是大年夜右向左依次调用的,先履行 g,接下来履行 f。

- // h(x) = x + 1
- // number -> number
- function h(x) {
- return x + 1;
- }
- // g(x) = x^2
- // number -> number
- function g(x) {
- return x * x;
- }
- // f(x) = convert x to string
- // number -> string
- function f(x) {
- return x.toString();
- }
- // y = (f ° g ° h)(1)
- const y = f(g(h(1)));
- console.log(y); // '4'
Ramda 和 lodash 之类的库供给了更优雅的方法来组合函数。我们可以在更多的在数学意义上处理函数组合,而不是简单地将一个函数的返回值传递给下一?函数。我们可以创建一个由这些函数构成的单一复合函数(就是 (f ° g)(x))。
- // h(x) = x + 1
- // number -> number
- function h(x) {
- return x + 1;
- }
- // g(x) = x^2
推荐阅读
如何处理JavaScript内存泄露
沙龙晃荡 | 去哪儿、陌陌、ThoughtWorks在主动化运维中的实践!10.28不见不散!
几周前,我们开端写一个系列,>>>详细阅读
本文标题:JavaScript的函数式编程,你了解吗?
地址:http://www.17bianji.com/lsqh/38230.html
1/2 1