Skip to content

Instantly share code, notes, and snippets.

@GheorgheP
Created April 23, 2017 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GheorgheP/f593e5579ca945687b2005d460c9ec77 to your computer and use it in GitHub Desktop.
Save GheorgheP/f593e5579ca945687b2005d460c9ec77 to your computer and use it in GitHub Desktop.
ES6 curry, with normal function behavior
const curry = f => {
const _curry = (args = []) => args.length < f.length ? (...a) => _curry([...args, ...a]) : f(...args)
return _curry()
}
@GheorgheP
Copy link
Author

You can use the curried function either like a partial function add(2)(3) or normal function add(2, 3)

Example:

const add = curry((a,b) => a+b)

console.log( add(1)(2) ); // >_ 3
console.log( add(1, 2) ); // >_ 3

//Increment every item from array
console.log( [1,2,3,4,5,6].map(add(1)) );

Dependency injection:

const _getUser = curry((dbConn, id) => dbConn.query(`SELECT * FROM users where users.id = ${id}`))

/*======================================*/
// No need to provide every time the connection in our environment
const getUser = _getUser(EVN.db.getConn)

console.log( _getUser(EVN.db.getConn, 12) );
console.log( getUser(12) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment