Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Created July 1, 2014 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AutoSponge/a2ef935291f99a9b9a93 to your computer and use it in GitHub Desktop.
Save AutoSponge/a2ef935291f99a9b9a93 to your computer and use it in GitHub Desktop.
function curry( arg ) {
var fn = this;
function curried( ...args ) {
return fn.apply( this, [arg, ...args] );
}
curried.curry = curry;
return curried;
}
function curry( arg ) {
var fn = this;
function curried() {
var args = [arg];
args.push.apply( args, arguments );
return fn.apply( this, args );
}
curried.curry = curry;
return curried;
}
var add = ( a, b ) => a + b;
var sum = ( ...args ) => [...args].reduce( add );
sum.curry = curry;
function sumThis( ...args ) {
return [...args].reduce( add, this );
}
sumThis.curry = curry;
console.assert( sum( 1, 2, 3 ) === 6, 'variadic sum works as expected' );
console.assert( typeof sum.curry( 1 ) === 'function', 'curry returns a function' );
console.assert( sum.curry( 1 )() === 1, 'executing a curried function returns' );
console.assert( sum.curry( 1 ).curry( 2 ).curry( 3 )() === 6, 'curry can chain' );
console.assert( curry.call( sum, 1 )() === 1, 'curry works with the call pattern' );
console.assert( curry.call( sum, 1 ).curry( 2 ).curry( 3 )( 4 ) === 10, 'curry can chain with the call pattern' );
console.assert( curry.apply( sum, [1] )( 2 ) === 3, 'curry works with the apply pattern' );
console.assert( curry.apply( sum, [1] ).curry( 2 )( 3 ) === 6, 'curry can chain with the apply pattern' );
console.assert( sumThis.apply( 1, [2, 3] ) === 6, 'variadic sumThis works as expected' );
console.assert( sumThis.curry( 1 ).curry( 2 ).apply( 3, [4] ) === 10, 'curried.apply uses the supplied context' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment