17. 组合函数原理模拟
leezozz 1/27/2023 js
const _ = require('lodash')
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
const f = _.flowRight( toUpper, first, reverse)
console.log(f(['one', 'two', 'three'])) // THREE
// 模拟 lodash 中的 flowRight
function compose (...arg) {
return function(value) {
return arg.reverse().reduce(function(acc, fn) {
return fn(acc)
}, value)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ES6写法
const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
const f = compose(toUpper, first, reverse)
console.log(f(['one', 'two', 'three'])) // THREE
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8