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 函数柯里化 #125

Open
GleanCoder1116 opened this issue Jan 24, 2021 · 0 comments
Open

Javascript 函数柯里化 #125

GleanCoder1116 opened this issue Jan 24, 2021 · 0 comments
Labels
高频面试 高频面试

Comments

@GleanCoder1116
Copy link
Member

实现一个聚合函数

sum(1,2,3).sumOf() // 6
sum(1)(2,3,4)(6).sumOf() // 16

结果如下:

function sum(...arg){
   const nums = [...arg]
   const pushArg = function(...arg){
        nums.push(...arg)
        return pushArg
    }
    pushArg.sumOf = function(){
        return nums.reduce((pre,now)=>{
           return pre +  now
        },0)
    }
    return pushArg
}

其实了解js的函数柯里化的话,这个题很好解决:

函数柯里化以Haskell Brooks Curry命名,柯里化是指将一个函数分解为一系列函数的过程,每个函数都只接收一个参数。(译注:这些函数不会立即求值,而是通过闭包的方式把传入的参数保存起来,直到真正需要的时候才会求值)

柯里化有3个常见作用:

  1. 参数复用;
  2. 提前返回;
  3. 延迟计算/运行

上面的那个题就是属于延迟计算/运行一个常见场景

提前返回

var  action= function(action) {
    var doing = function(doing) {
        var result = "";
        if (action === "action1") {
            if (doing === "doing1") {
                result = "doing1";
            } else if (doing === "doing2") {
                result = "doing2";
            }
        } else {
            if (doing === "doing3") {
                result = "doing3";
            } else if (doing === "doing4") {
                result = "doing4";
            }
        }
        console.log(result);
       return doing
    };
    return doing;
};

action("action1")("doing1")("doing2");

参数 action1action函数使用的,接下来的doing1doing2都是内部doing函数使用;这个时候有个概念大家一定要知道关于闭包的感念;不懂的可以试下去看看

参数复用

// 正常正则验证字符串 reg.test(txt)

// 函数封装后
function check(reg, txt) {
    return reg.test(txt)
}

check(/\d+/g, 'test')       //false
check(/[a-z]+/g, 'test')    //true

// Currying后
function curryingCheck(reg) {
    return function(txt) {
        return reg.test(txt)
    }
}

var hasNumber = curryingCheck(/\d+/g)
var hasLetter = curryingCheck(/[a-z]+/g)

hasNumber('test1')      // true
hasNumber('testtest')   // false
hasLetter('21212')      // false
@GleanCoder1116 GleanCoder1116 added the 高频面试 高频面试 label Jan 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
高频面试 高频面试
Projects
None yet
Development

No branches or pull requests

1 participant