We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Higher-order functions are functions that accept (as parameters) and/or return other functions.
The text was updated successfully, but these errors were encountered:
首先给出实现:
// 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) } }
Sorry, something went wrong.
No branches or pull requests
The text was updated successfully, but these errors were encountered: