JavaScript函数式编程-柯里化(currying)(五)

柯里化概念
柯里化的概念很简单:只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数。
你可以一次性地调用 curry 函数,也可以每次只传一个参数分多次调用。

柯里化作用

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

示例:

// 平时喜欢的写法
var sentence = function(name, hobby, friend) {
 return name + ' like ' + hobby + ' with ' + friend;
}

console.log(sentence('john', 'play games', 'tom'));
// john like play games with tom

// 将函数使用柯里化重写
var sentence = function(name){
 return function(hobby){
 return function(friend){
 return name + ' like ' + hobby + ' with ' + friend;
 }
 }
}

console.log(sentence('john')('play games')('tom'));
// john like play games with tom

//使用es6重写
var sentence =
 name =>
 hobby =>
 friend =>
 name + ' like ' + hobby + ' with ' + friend

console.log(sentence('john')('play games')('tom'));
// john like play games with tom

// 将sentence('john')('play games')('tom')拆分一下
var part1 = sentence('john');
var part2 = part1('play games');
console.log(part2('tom'));
// john like play games with tom

下载curry帮助函数使这类函数的定义和调用更加容易

npm install lodash

var curry = require('lodash').curry;
var sentence = function(name, hobby, friend) {
 return name + ' like ' + hobby + ' with ' + friend;
};
sentence = curry(sentence);
console.log(sentence('john')('play games')('tom'));
// john like play games with tom

你可能感兴趣的:(JavaScript函数式编程-柯里化(currying)(五))