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

第166题:闭包 JS基础 编程题 (字节) #455

Open
yellowjian opened this issue Apr 1, 2021 · 8 comments
Open

第166题:闭包 JS基础 编程题 (字节) #455

yellowjian opened this issue Apr 1, 2021 · 8 comments
Labels

Comments

@yellowjian
Copy link

yellowjian commented Apr 1, 2021

var foo = function(...args) { // 要求实现函数体}
var f1 = foo(1,2,3); f1.getValue(); // 6 输出是参数的和
var f2 = foo(1)(2,3); f2.getValue(); // 6
var f3 = foo(1)(2)(3)(4); f3.getValue(); // 10

@yellowjian yellowjian reopened this Apr 1, 2021
@wendao-liu
Copy link

Function.prototype.getValue = function () {
    let num = this.arr.reduce((x, y) => (x + y))
    this.arr = null
    return num
  }
  var foo = function (...args) {
    if (!Array.isArray(foo.arr)) {
      foo.arr = []
    }
    foo.arr.push(...args)
    return foo;
  }

@Yang-yibu
Copy link

function foo(...args) {
  foo.value = args.reduce((total, cur) => total + cur, (foo.value || 0))
  return foo
}

foo.getValue = function () {
  var value = this.value;
  this.value = 0;
  return value
}

@Ishmael-Yoko
Copy link

function foo(...args) {
  const target = (...arg1s) => foo(...[...args, ...arg1s])
  target.getValue = () => args.reduce((p, n) => p+ n, 0)
  return target
}

@yellowjian
Copy link
Author

@Ishmael-Yoko 不错,大概跟面试官想要的一致。

@xiaoerwen
Copy link

const foo = function() {
    let args = Array.prototype.slice.call(arguments);
    const target = function() {
        args = args.concat(Array.prototype.slice.call(arguments));
        return foo(...args);
    };
    target.getValue = () => args.reduce((x, y) => x + y, 0);
    return target;
};

@nomyfan
Copy link

nomyfan commented May 8, 2021

function foo(...args) {
  const sum = args.reduce((acc, v) => acc + v, 0);

  const hof = function (...args) {
    return foo(sum, ...args);
  };
  hof.getValue = () => sum;

  return hof;
}

@JYone223
Copy link

const foo = (...args) => {
  const _add = (...args1) => {
    return foo(...args, ...args1);
  }

  _add.getValue = () => args.reduce((acc, cur) => acc + cur);

  return _add;
}

@jackluson
Copy link

Tip:

  1. 返回值是一个函数
  2. 动态参数,拼接参数,getValue 统一计算
function foo(...args) {
  let addArgs = [...args];
  function fn(...innerArgs) {
    addArgs = [...addArgs, ...innerArgs];
    return fn;
  }
  fn.getValue = function () {
    return addArgs.reduce((pre, cur) => {
      return pre + cur;
    }, 0);
  };
  return fn;
}

const sum = foo(1, 2, 3)(2)(3).getValue();
// const sum = foo(1, 2, 3).getValue();
console.log("sum", sum);

更多解析

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

No branches or pull requests

9 participants