请实现一个模块 math,支持链式调用math.add(2,4).minus(3).times(2);
Sunny-117 opened this issue · comments
class math {
constructor(initValue = 0) {
this.value = initValue;
}
add(...args) {
this.value = args.reduce((pre, cur) => pre + cur, this.value);
return this;
}
minus(...args) {
this.value = this.value - args.reduce((pre, cur) => pre + cur);
return this;
}
times(timer) {
this.value = timer * this.value;
return this;
}
getVal() {
return this.value;
}
}
class math {
constructor(value = 0) {
this.value = value;
}
add(...args) {
this.value = args.reduce(
(ljq, cur) => ljq + cur,
this.value
);
return this;
}
minus(...args) {
this.value =
this.value - args.reduce((ljq, cur) => ljq + cur);
return this;
}
times(...args) {
this.value *= args.reduce((ljq, cur) => ljq * cur);
return this;
}
}
let m = new math(2);
console.log(m.times(3, 4, 5));
const math = {
result: 0,
add: function (...args) {
this.result += args.reduce((pre, cur) => pre + cur, this.result);
return this;
},
minus: function (value) {
this.result -= value;
return this;
},
times: function (value) {
this.result *= value;
return this;
},
getResult: function () {
return this.result;
}
};
// test code
const result = math.add(2, 4).minus(3).times(2).getResult();
console.log(result); // 输出: 6
这个题有两种想法:
- op 操作:将每一次函数调用视为一个 op 维护在一个数组中,当要通过一个方法获取之前操作的最后结果的时候,遍历所有 op,执行计算
- 在每一次调用过程中,实时计算一个值,最后返回的时候也是这个值
class Math {
constructor(value = 0) {
this.value = value;
}
add(...args) {
this.value = args.reduce((acc, cur) => acc + cur, this.value);
return this;
}
minus(...args) {
this.value = args.reduce((acc, cur) => acc - cur, this.value);
return this;
}
times(...args) {
this.value = args.reduce((acc, cur) => acc * cur, this.value);
return this;
}
}
const math = new Math();
console.log(math.add(2, 4).minus(1).times(2, 4));