参考文章—函数式编程 Lodash 中文文档

    1. var curry = require('lodash').curry;
    2. var match = curry(function(what, str) {
    3. return str.match(what);
    4. });
    5. var replace = curry(function(what, replacement, str) {
    6. return str.replace(what, replacement);
    7. });
    8. var filter = curry(function(f, ary) {
    9. return ary.filter(f);
    10. });
    11. var map = curry(function(f, ary) {
    12. return ary.map(f);
    13. });

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

    1. match(/\s+/g, "hello world");
    2. // [ ' ' ]
    3. match(/\s+/g)("hello world");
    4. // [ ' ' ]
    5. var hasSpaces = match(/\s+/g);
    6. // function(x) { return x.match(/\s+/g) }
    7. hasSpaces("hello world");
    8. // [ ' ' ]
    9. hasSpaces("spaceless");
    10. // null
    11. filter(hasSpaces, ["tori_spelling", "tori amos"]);
    12. // ["tori amos"]
    13. var findSpaces = filter(hasSpaces);
    14. // function(xs) { return xs.filter(function(x) { return x.match(/\s+/g) }) }
    15. findSpaces(["tori_spelling", "tori amos"]);
    16. // ["tori amos"]
    17. var noVowels = replace(/[aeiou]/ig);
    18. // function(replacement, x) { return x.replace(/[aeiou]/ig, replacement) }
    19. var censored = noVowels("*");
    20. // function(x) { return x.replace(/[aeiou]/ig, "*") }
    21. censored("Chocolate Rain");
    22. // 'Ch*c*l*t* R**n'

    :::info 这里表明的是一种“预加载”函数的能力,通过传递一到两个参数调用函数,就能得到一个记住了这些参数的新函数。 :::