add(1)(2)(3)(4)
可以实现任意数量数字相加,但是需要用+号隐式转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function fn() { let result = []; function add(...args) { result = [...result, ...args] return add; }; add.toString = () => result.reduce((sum, k) => sum + k, 0); return add; }; let add = fn() console.log(+add(1)(2)(3)(4)) console.log(+add2(1, 2, 3)(4))
|
参数固定的情况下,不需要用+号,可以根据参数长度来判断返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function currying(fn, length) { length = length || fn.length; return function (...args) { return args.length >= length ? fn.apply(this, args) : currying(fn.bind(this, ...args), length - args.length) } } function fn(a, b, c, d) { return a + b + c + d } const add = currying(fn) add(4)(3)(1)(2) add(1, 3)(4)(2) add(1)(3, 4, 2)
|