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

请实现一个 add 函数,满足以下功能 #69

Open
susouth opened this issue Dec 9, 2019 · 0 comments
Open

请实现一个 add 函数,满足以下功能 #69

susouth opened this issue Dec 9, 2019 · 0 comments
Labels
JavaScript 跟js相关的面试题 No.76

Comments

@susouth
Copy link
Contributor

susouth commented Dec 9, 2019

📚在线阅读:前端人员需要了解的传值机制 - No.76

一个考函数式编程(柯里化函数)的问题。

解题1:

function currying(fn, length) {
  length = length || fn.length; 	// 注解 1
  return function (...args) {			// 注解 2
    return args.length >= length	// 注解 3
    	? fn.apply(this, args)			// 注解 4
      : currying(fn.bind(this, ...args), length - args.length) // 注解 5
  }
}

解题2:

const currying = fn =>
    judge = (...args) =>
        args.length >= fn.length
            ? fn(...args)
            : (...arg) =judge(...args, ...arg)

注解说明:

  • 注解 1:第一次调用获取函数 fn 参数的长度,后续调用获取 fn 剩余参数的长度
  • 注解 2:currying 包裹之后返回一个新函数,接收参数为 ...args
  • 注解 3:新函数接收的参数长度是否大于等于 fn 剩余参数需要接收的长度
  • 注解 4:满足要求,执行 fn 函数,传入新函数的参数
  • 注解 5:不满足要求,递归 currying 函数,新的 fn 为 bind 返回的新函数(bind 绑定了 ...args 参数,未执行),新的 length 为 fn 剩余参数的长度

解题3:

使用了一个闭包完成了这个效果

function add(...num) {
    let res = 0 //第一次调用函数时生成一个闭包来存储结果
    num.forEach(item => res += item) //遍历输入参数加到res上
    let ret = function (...num) {
      num.forEach(item => res += item)
      return ret
    }
    ret.toString = function () {
      return res
    }
    ret.valueOf = function () {
      return res
    }
    return ret
  }
  console.log(add(1)); // 1
  console.log(add(1)(2)); // 2
  console.log(add(1)(2)(3)); // 6
  console.log(add(1)(2)(3,7)(4,5,6));// 28

解题4 ?:

👇~~~~ 欢迎在下方评论补充你的答案,一起来学习~:pushpin:

更多内容

@susouth susouth added JavaScript 跟js相关的面试题 No.76 labels Dec 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 跟js相关的面试题 No.76
Projects
None yet
Development

No branches or pull requests

1 participant