认识 科里化(curry)——JS函数式编程

科里化函数

概念: 只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。ui

var add = function(x) {

    return function(y) {
        return x + y;
    };
};

var increment = add(1);
var addTen = add(10);

increment(2);

addTen(2);

只定义了一个 add 函数,他接受一个参数并返回一个新的函数,调用 add 以后,返回的函数就经过必报的方式记住了 add 的第一个参数。一次性地调用它是在是有点繁琐,好在咱们能够使用一个特殊的curry帮助函数使这类函数的定义和调用更加容易。code

var curry = require('lodash').curry;

var match = curry(function(what,str){
    return str.match(what);
});

var replace = curry(function(what, replacement, str){
    return str.replace(what, replacement);
});

var filter = curry(function(f, ary) {
    return ary.filter(f);
});

var map = curry(function(f, ary) {
    return ary.map(f);
});

我在上面的代码中遵循的是一种简单,同时也很是重要的模式。即策略性地把要操做的数据(string, Array)放到最后一个参数里。到使用它们的时候就明白这么作的缘由是什么了。rem

match(/\s+/g, "hello world");
// [ ' ' ]

match(/\s+/g)("hello world");
// [ ' ' ]

var hasSpaces = match (/\s + /g);
// function(x) { return x.match(/\s+/g) }

hasSpaces("hello World");
// [ ' ']
相关文章
相关标签/搜索