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

一个有味道的函数 #80

Open
zanjs opened this issue Mar 30, 2018 · 1 comment
Open

一个有味道的函数 #80

zanjs opened this issue Mar 30, 2018 · 1 comment

Comments

@zanjs
Copy link
Owner

zanjs commented Mar 30, 2018

最近想到了一个自认为很有意思的面试题
如何实现一个 compose 函数。
函数接收数个参数,参数均为 Function 类型,右侧函数的执行结果将作为左侧函数执行的参数来调用。

原文

@zanjs
Copy link
Owner Author

zanjs commented Mar 6, 2019

1.0实现方案

大致的思路为:

  • 获取所有的参数
  • 调用最后一个函数,并接收返回值
  • 如果没有后续的函数,返回数据,如果有,将返回值放入下一个函数中执行

所以这种情况用递归来实现会比较清晰一些

function compose (...funcs) {
  return function exec (arg) {
    let func = funcs.pop()
    let result = func(arg) // 执行函数,获取返回值

    // 如果后续还有函数,将返回值放入下一个函数执行
    // 如果后续没有了,直接返回
    return funcs.length ? exec(result) : result
  }
}

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