偏应用函数 Partial Application
栗子:
// 创建偏应用函数,偏应用函数将会返回另一个函数。
// 带一个函数参数 和 该函数的部分参数
const partial = (f, ...args) =>
// 返回一个函数:这个函数的参数在调用函数的时候传入。
(...moreArgs) =>
// 使用全部参数调用原始函数
f(...args, ...moreArgs)
// 原始函数
const add3 = (a, b, c) => a + b + c
// 偏应用 `2` 和 `3` 到 `add3` 给你一个单参数的函数
const fivePlus = partial(add3, 2, 3) // (c) => 2 + 3 + c
fivePlus(4) // 9
Currying
函数柯里化
const sum = (a, b) => a + b
const curriedSum = (a) => (b) => a + b
curriedSum(40)(2) // 42.
const add2 = curriedSum(2) // (b) => 2 + b
add2(10) // 12
将多元函数转化为多次调用一元函数就是函数柯里化。
函数合成 Function Composition
将多个函数合成在一起构成一个新的函数,其中后一个函数的输出将作为前一个函数的输入。
const compose = (f, g) => (a) => f(g(a))
const floorAndToString = compose((val) => val.toString(), Math.floor)
floorAndToString(121.212121) // '121'
纯函数
如果返回值仅由其输入值决定,并且不产生副作用,那么这个函数就是纯函数。
惰性求值 Lazy evaluation
使用了ES6的 Generator 函数。
详见:http://es6.ruanyifeng.com/#docs/generator
const rand = function*() {
while (1 < 2) {
yield Math.random()
}
}
const randIter = rand()
randIter.next() // 每个执行都给出一个随机值,表达式按需求值。