字节编程题:实现一个add方法
sisterAn opened this issue · 8 comments
sisterAn commented
例如:
add(1)(2,3)(4).value()
输出: 10
kexiaofu commented
先来抛砖,希望可以引玉
function add() {
const args = Array.prototype.slice.apply(arguments);
const self = this;
this.nums = [...args];
function _add() {
const _args = Array.prototype.slice.apply(arguments);
this.nums.push(..._args);
return _add;
}
_add.value = function() {
return self.nums.reduce((acc, cur) => acc += cur, 0);
}
return _add;
}
考验的是闭包和this
oxyzhg commented
function add(...args) {
const nums = [...args];
function addFn(...args1) {
nums.push(...args1);
return addFn;
}
addFn.value = () => {
const sum = nums.reduce((s, n) => s + n, 0);
console.log(sum);
return sum;
};
return addFn;
}
m7yue commented
思路都差不多
const add = (...args) => {
const _add = (...args1) => {
return add(...args, ...args1)
}
_add.value = () => args.reduce((t, e) => t+e)
return _add
}
add(1)(2,3)(4).value()
feng9017 commented
function add(...params) {
const result = add.bind(null, ...params);
result.value = () => params.reduce((accumulator, cur) => accumulator + cur);
return result;
}
z253573760 commented
function add(...args) {
const _add = (..._args) => {
args.push(..._args);
return _add;
};
_add.value = () => args.reduce((a, b) => a + b, 0);
return _add;
}
const res = add(1)(2, 3)(4).value(); //10
console.log(res);
dlrandy commented
function add(...params) {
let args = [...params];
function innerAdd(...p) {
args = args.concat(p);
return innerAdd;
}
function value() {
return args.reduce((s, n) => s + n , 0)
}
innerAdd.value = value;
return innerAdd;
}
xllpiupiu commented
/**
* 函数柯里化实现add(1)(1,2)(3)等
* https://blog.csdn.net/weixin_30498807/article/details/102319249
*/
// let obj = {
// name:'hell',
// toString:function() {
// console.log('调用了toString')
// return '22'
// },
// valueOf:function() {
// console.log('调用了obj.valueOf');
// return '00'
// }
// }
// console.log(obj+"3")
function test() {
console.log(1);
}
test.toString = function () {
console.log('调用了valueOf方法');
return 2;
}
function add() {
var arr = Array.prototype.slice.call(arguments)
const _adder = function () {
arr.push(...arguments)
return _adder;
}
_adder.valueOf = function () {
return arr.reduce((a, b) => a + b);
}
return _adder;
}
let res = add(1)(2)(3, 4);
console.log(add(1)(2, 3).valueOf())
console.log(res+0)
liu-mengwei commented
function add(...args1) {
let _add = function (...args2) {
return add(...args1, ...args2);
};
_add.value = function () {
let sum = 0;
for (let num of args1) {
sum += num;
}
return sum;
};
return _add;
}