Skip to content

Latest commit

 

History

History
57 lines (48 loc) · 1.27 KB

5.2.2.1-自动柯里化参数.md

File metadata and controls

57 lines (48 loc) · 1.27 KB

Code

柯里化两个参数的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)