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.手写一个偏函数 #7

Open
webVueBlog opened this issue May 22, 2022 · 0 comments
Open

5.手写一个偏函数 #7

webVueBlog opened this issue May 22, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

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

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

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

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

addOne(2) // 3
const partial = (fn, ...restArgs) => {
 // 默认参数和新传递的参数进行组合,然后调用方法
 return (...args) => func(...restArgs, ...args);
};

柯里化是将一个多参数函数转换成多个单参数函数,也就是将一个n元函数转换成n个一元函数。

局部应用则是固定一个函数的一个或者多个参数,也就是将一个n元函数转换成一个 n - x 元函数。

// 偏函数是柯里化的子集
function addParti(fn, ...args) {
 return function(...newArgs) {
  return fn(...args, ...newArgs);
 }
}
const partial = function() {
 const fn = Array.prototype.shift.call(arguments);
 const arg1 = [...arguments];
 return function() {
  const arg2 = [...arg1, ...arguments];
  return fn.call(this, ...arg2);
 }
}
function Partial(fn: Function, ...args: any[]) {
 return (...rest: any[]) => fn(...args, ...rest);
}
function partial(func, ...restArgs) {
 return function(...args) {
  return func.call(this, ...restArgs, ...args);
 }
}

箭头函数:

function addParti(fn, ...args) {
 return (...newArgs) => fn(...args, ...newArgs);
}
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