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

JS 之高阶函数 #54

Open
evantianx opened this issue Aug 23, 2017 · 1 comment
Open

JS 之高阶函数 #54

evantianx opened this issue Aug 23, 2017 · 1 comment

Comments

@evantianx
Copy link
Owner

evantianx commented Aug 23, 2017

1-0szq6eu5nuo_vygzcjbida

Higher-order functions are functions that accept (as parameters) and/or return other functions.

@evantianx
Copy link
Owner Author

evantianx commented Aug 23, 2017

偏函数 partial function

首先给出实现:

// ES6 实现
function partial(fn, ...args) {
  return function(...newArgs) {
    return fn.apply(this, args.concat(newArgs))
  }
}
// ES5 实现
function partial(fn) {
  var fixed = [].slice.apply(arguments, [1])
  return function() {
    var args = fixed.concat([].slice.apply(arguments))
    return fn.apply(this, args)
  }
}

这样,比如想要计算一个乘法:

function multiple(a, b) {
  return a * b
}
var double = partial(multiple, 2)
console.log(double(5)) // 10

可以看出,偏函数大大加强了某些函数的重用性,我们无需再去重复不必要的代码就可以达到所想要的效果。

但是可以发现上述的实现有一个很严重的问题:

function divide(a, b) {
  return a / b
}
var half = partial(divide, 2)
console.log(half(5)) //  期待值为 2.5 ,实际为 0.4

这样我们应当实现一个类似于 lodash 中的占位符 _,可以用来省略参数:

此实现来源于 JavaScript专题之偏函数
作者 @mqyqingfeng

var _ = {}

function partial(fn) {
  var args = [].slice.call(arguments, 1)
  return function () {
    var position = 0, len = args.length
    for (var i = 0; i< len; i++) {
      // 若 args[i] 等于 _ ,说明此处的值应当从第二层传入的参数中取
      args[i] = args[i] === _ ? arguments[position++] : args[i]
    }
    while (position < arguments.length) args.push(arguments[position++])
    return fn.apply(this, args)
  }
}

@evantianx evantianx changed the title JS 之 高阶函数 JS 之高阶函数 Sep 8, 2017
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