贴一下自己的答案: 加
function sum(){
const result = [...arguments].reduce((acc, cur)=>acc+cur)
return function(){
if(arguments.length === 0)return result
return sum(...[...arguments, result]);
}
}
柯里化的加减乘除
function curry(callback){
return function curried (){
const result = callback(arguments)
return function(){
if(arguments.length === 0)return result
return curried(...[result, ...arguments]);
}
}
}
let sum = (args) =>{
return [...args].reduce((acc, cur)=>acc+cur)
}
let minus = (args) =>{
return [...args].reduce((acc, cur)=>acc-cur)
}
let multiple = (args) =>{
return [...args].reduce((acc, cur)=>acc*cur)
}
let divide = (args) =>{
return [...args].reduce((acc, cur)=>acc / cur)
}
let currySum = curry(sum)
let curryMultiple = curry(multiple)
let curryDivide = curry(divide)
let curryMinus = curry(minus)
console.log(currySum(1,2,3)(4)(5)(6,7)(8)())
console.log(curryMultiple(1,2,3)(4)(5)(6,7)(8)())
console.log(curryDivide(1,2,3)(4)(5)(6,7)(8)())
console.log(curryMinus(1,2,3)(4)(5)(6,7)(8)())
1
powerfulyang 2021-03-26 19:55:37 +08:00 via iPhone
柯里化
|
2
imdong 2021-03-26 20:09:50 +08:00
function add() {
let nums = Array.from(_args); return function () { nums = nums.concat(Array.from(_args)); if (arguments.length <= 0) { return nums.reduce(function (prev, cur) { return prev + cur; }, 0); } return arguments.callee; }; } add(1, 2, 3)(4)(5)(6, 7)(8)() |
3
imdong 2021-03-26 20:10:56 +08:00
呃,变量名忘记改了,_args 应改为 arguments
正确代码应该是: function add() { let nums = Array.from(arguments); return function () { nums = nums.concat(Array.from(arguments)); if (arguments.length <= 0) { return nums.reduce(function (prev, cur) { return prev + cur; }, 0); } return arguments.callee; }; } add(1, 2, 3)(4)(5)(6, 7)(8)() |
4
Elethom 2021-03-26 21:50:39 +08:00
|
6
enchilada2020 2021-03-26 22:29:45 +08:00
优化了下 #3 的代码 有错请轻喷。。
```JavaScript const infiniteAdd = function () { const args = [...arguments]; return function f() { if (!arguments.length) return args.reduce((acc, cur) => acc + cur, 0); args.push(...arguments); return f; } }; console.log(infiniteAdd(1, 2, 3)(4, 5)(6)(7, 8, 9, 10)(11, 12)()); // 78 ``` |
7
IsaacYoung 2021-03-26 22:38:43 +08:00
function curry(fn) {
let p = []; const wrapper = function (...args) { if(args.length) { p = p.concat(args); return wrapper } else { return fn(...p) } } return wrapper } function addOriginal (...args) { return args.reduce((prev, curr) => prev + curr, 0) } const add = curry(addOriginal) |
8
muxw6 2021-03-26 22:55:05 +08:00 2
function add(...args) {
return function(..._args) { return _args.length>0 ? add(...args, ..._args) : args.reduce((a, c) => a + c) } } |
10
iMusic 2021-03-27 09:45:25 +08:00
以前见过类似的题
``` sum(2)(3) 和 sum(2, 3) ``` |