js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

请实现一个模块 math,支持链式调用math.add(2,4).minus(3).times(2);

Open Sunny-117 opened this issue 2 years ago • 5 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

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;
  }
}

weirong111 avatar Nov 06 '22 14:11 weirong111

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));

cscty avatar Jul 04 '23 17:07 cscty

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

mafeiGitHub avatar Oct 16 '23 05:10 mafeiGitHub

这个题有两种想法:

  1. op 操作:将每一次函数调用视为一个 op 维护在一个数组中,当要通过一个方法获取之前操作的最后结果的时候,遍历所有 op,执行计算
  2. 在每一次调用过程中,实时计算一个值,最后返回的时候也是这个值

hexianga avatar Nov 17 '23 15:11 hexianga

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));

wmdmomo avatar May 30 '24 07:05 wmdmomo