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

JavaScript模拟实现函数柯里化和反柯里化 #15

Open
GGXXMM opened this issue Aug 9, 2019 · 0 comments
Open

JavaScript模拟实现函数柯里化和反柯里化 #15

GGXXMM opened this issue Aug 9, 2019 · 0 comments
Labels
⭐️ js js knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 9, 2019

一、柯里化

什么是函数柯里化?

官方的说法

在计算机科学中,柯里化(英语:Currying),又译为卡瑞化或加里化,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术。

简单的理解

柯里化是一种闭包的运用,分多次接收参数,延迟计算。

js函数柯里化使用

// 柯里化函数
function curry(a) {
  return function(b) {
    return function(c) {
        return a + b + c;
    }
  }
}
function add(a, b, c) {
    return a + b + c
}
add(1, 2, 3)
let addCurrying = curry(add)

// 调用柯里化函数
addCurrying(1)(2)(3) // 6

js函数柯里化的作用

主要为以下常见的三个用途:

  • 延迟计算
  • 参数复用
  • 动态生成函数

模拟实现js函数柯里化

function curry(fn, args) {
    // 获取fn函数的形参数
    var length = fn.length;
    var args = args || [];
    return function() {
    	newArgs = args.conact(Array.prototype.slice.call(arguments));
        // 当收集参数少于length,继续收集参数
    	if (newArgs.length < length) {
    		return curry.call(this, fn, newArgs);
    	} else {// 所有参数收集完毕,整体执行fn函数
    		return fn.apply(this, newArgs)
    	}
    }
}

function multiFn(a, b, c) {
    return a * b * c;
}

var multi = curry(multiFn);

multi(2)(3)(4);
multi(2,3,4);
multi(2)(3,4);
multi(2,3)(4);

二、反柯里化

什么是反柯里化?

反柯里化(unCurry),是扩大函数的适用性,使特定对象拥有的功能函数,可以被任意对象调用。

反柯里化使用

var test="a,b,c";
console.log(test.split(","));

var split=uncurrying(String.prototype.split);   //[ 'a', 'b', 'c' ]
console.log(split(test,','));                   //[ 'a', 'b', 'c' ]

反柯里化实现

function unCurry(fn) {
    return function() {
        var obj = [].shift.call(arguments);// 删除并返回第一项
        return fn.apply(obj, arguments)
    }
}
@GGXXMM GGXXMM changed the title JavaScript模拟实现js函数柯里化 JavaScript模拟实现函数柯里化 Jan 19, 2021
@GGXXMM GGXXMM added the ⭐️ js js knowledge label Dec 7, 2021
@GGXXMM GGXXMM changed the title JavaScript模拟实现函数柯里化 JavaScript模拟实现函数柯里化和反柯里化 Mar 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⭐️ js js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant