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

4.实现一个sum函数 #6

Open
webVueBlog opened this issue May 21, 2022 · 0 comments
Open

4.实现一个sum函数 #6

webVueBlog opened this issue May 21, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

  1. sum函数可以传递一个或者多个参数
  2. sum函数调用后返回的是一个新的函数且参数可传递一个或者多个
  3. 调用.valueOf时完成最后计算
sum(1, 2, 3).valueOf() // 6
sum(2, 3)(2).valueOf() // 7
sum(1)(2)(3)(4).valueOf() // 10
sum(2)(4, 1)(2).valueOf() // 9
const sum = () => {
 let args = [...arguments];
 const func = () => {
  args = [...args, ...arguments];
  return func;
 }
 func.valueOf = () => args.reduce((cur, prev) => cur + prev);
 return func;
}
const sum = (...args1) => {
  const fullArgs = [...args1];
  const fn = (...args2) => {
    // 收集参数
    fullArgs.push(...args2)
    // 返回自身保持链式调用
    return fn;
  };

  // 重写valueOf,累加已收集的参数
  fn.valueOf = () => fullArgs.reduce((total, cur) => total + cur)

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

1 participant