-
Notifications
You must be signed in to change notification settings - Fork 0
/
compose.js
56 lines (47 loc) · 1.24 KB
/
compose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 组合
// compose(f,g)(x) === f(g(x))
// compose(f,g,m)(x) === f(g(m(x)))
// compose(f,g,m)(x) === f(g(m(x)))
// compose(f,g,m,n)(x) === f(g(m(n(x))))
// 我们需要借助reduce
// compose的调用顺序是从右到左依次调用函数
// pipeline的的调用顺序是从做到右依次调用函数
function compose(...fns) {
return function (x) {
return fns.reduceRight(function (arg, fn) {
return fn(arg);
}, x);
};
}
function pipe(...fns) {
return function (x) {
return fns.reduce(function (arg, fn) {
return fn(arg);
}, x);
};
}
function toUpperCase(str) {
return str.toUpperCase();
}
function toReverse(str) {
return str.split("").reverse().join("");
}
const composedFun = pipe(toUpperCase, toReverse);
console.log(composedFun("abc"));
// 使用递归完成组合的功能
function recursionCompose(...args) {
//参数1
let count = args.length - 1;
let result;
return function fn(...arg1) {
//参数2
result = args[count].apply(null, arg1);
if (count <= 0) {
return result;
}
count--;
return fn.call(null, result);
};
}
const a = recursionCompose(toUpperCase, toReverse); //参数1
console.log(a("jkl")); //参数2