柯里化两个参数的curry2函数
function curry2(fun) {
return function(secondArg) {
return function(firstArg) {
return fun(firstArg, secondArg);
};
};
}
underscore的countBy
函数的使用例子:
var plays = [{artist : 'tom', track : 'country'},
{artist : 'tom1', track : 'country1'},
{artist : 'tom2', track : 'country2'}];
_.countBy(plays, function(song) {
return [song.artist, song.track].join(" - ")
})
<. Object {tom - country: 1, tom1 - country1: 1, tom2 - country2: 1}
使用curry2
来使code的可读性更高
function songToString(song) {
return [song.artist, song.track].join(' - ')
}
var songCount = curry2(_.countBy)(songToString)
songCount(plays)
<. Object {tom - country: 1, tom1 - country1: 1, tom2 - country2: 1}
柯里化三个参数:
function curry3(fun) {
console.log('execute curry3 and return function')
return function(last) {
console.log('last:', last)
return function(middle) {
console.log('middle:', middle)
return function(first) {
console.log('first:', first, 'middle:', middle, 'last:', last)
return fun(first, middle, last)
}
}
}
}
curry3(_.unique)(songToString)(false)(plays)