Skip to content

Instantly share code, notes, and snippets.

@getify
Last active February 13, 2017 06:50
Show Gist options
  • Select an option

  • Save getify/54b9f231a771ea2fed7464d3aa46ff16 to your computer and use it in GitHub Desktop.

Select an option

Save getify/54b9f231a771ea2fed7464d3aa46ff16 to your computer and use it in GitHub Desktop.
curryProps + partialProps + spreadArgProps
function curryProps(fn,arity = 1) {
return (function nextCurried(prevArgs){
return function curried(nextArg){
if (!nextArg || typeof nextArg != "object") {
nextArg = { value: nextArg };
}
var [key] = Object.keys( nextArg );
var args = Object.assign( {}, prevArgs, { [key]: nextArg[key] } );
if (Object.keys( args ).length >= arity) {
return fn( args );
}
else {
return nextCurried( args );
}
};
})( {} );
}
function partialProps(fn,presetArgsObj) {
return function partiallyApplied(laterArgsObj){
return fn( Object.assign( {}, presetArgsObj, laterArgsObj ) );
};
}
function spreadArgProps(
fn,
propOrder = fn.toString()
.replace( /^(?:(?:function.*\(([^]*?)\))|(?:([^\(\)]+?)\s*=>)|(?:\(([^]*?)\)\s*=>))[^]+$/, "$1$2$3" )
.split( /\s*,\s*/ )
.map( v => v.replace( /[=\s].*$/, "" ) )
) {
return function spreadFn(argsObj) {
return fn( ...propOrder.map( k => argsObj[k] ) );
};
}
function foo({ x, y, z } = {}) {
console.log( `foo | x:${x} y:${y} z:${z}` );
}
function bar(x,y,z) {
console.log( `bar | x:${x} y:${y} z:${z}` );
}
var f1 = curryProps( foo, 3 );
var f2 = partialProps( foo, {y: 2} );
var f3 = curryProps( spreadArgProps( bar ), 3 );
var f4 = partialProps( spreadArgProps( bar ), {y: 2} );
f1( {y: 2} )( {x: 1} )( {z: 3} );
// foo | x:1 y:2 z:3
f2( {z: 3, x: 1} );
// foo | x:1 y:2 z:3
f3( {y: 2} )( {x: 1} )( {z: 3} );
// bar | x:1 y:2 z:3
f4( {z: 3, x: 1} );
// bar | x:1 y:2 z:3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment