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

5.实现一个偏函数 #5

Open
gumingWu opened this issue May 22, 2022 · 1 comment
Open

5.实现一个偏函数 #5

gumingWu opened this issue May 22, 2022 · 1 comment

Comments

@gumingWu
Copy link
Owner

这次的题也是对前三个的复习!大家加油
一篇羽大大文章镇楼 JavaScript专题之偏函数

在计算机科学中,局部应用是指固定一个函数的一些参数,然后产生另一个更小元的函数。

什么是元?元是指函数参数的个数,比如一个带有两个参数的函数被称为二元函数

function add(a, b) {
    return a + b;
}

// 执行 add 函数,一次传入两个参数即可
add(1, 2) // 3

// 假设有一个 partial 函数可以做到局部应用
var addOne = partial(add, 1);

addOne(2) // 3
@LuMMao
Copy link

LuMMao commented May 23, 2022

// 偏函数也可以理解为一种特殊的柯里化函数,是功能为参数复用的柯里化函数
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] === _ ? arguments[position++] : args[i];
    }
    while (position < arguments.length) args.push(arguments[position++]);
    return fn.apply(this, args);
  };
}

var subtract = function (a, b) {
  return b - a;
};
subFrom20 = partial(subtract, _, 20);
console.log(subFrom20(5));

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

2 participants