Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@weirong111
Copy link

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

@cscty
Copy link

cscty commented Jul 4, 2023

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

@mafeiGitHub
Copy link

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

@hexianga
Copy link

hexianga commented Nov 17, 2023

这个题有两种想法:

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

@wmdmomo
Copy link

wmdmomo commented May 30, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants