Skip to content

Instantly share code, notes, and snippets.

@Maximilianos
Last active May 8, 2016 23:15
Show Gist options
  • Save Maximilianos/127f3226d77186a568918638ea5cc22c to your computer and use it in GitHub Desktop.
Save Maximilianos/127f3226d77186a568918638ea5cc22c to your computer and use it in GitHub Desktop.
Curry a function in JavaScript
/**
* Curry the given function
*
* @param func {Function} the function to curry
* @param context {Object} (optional) the execution context to
* apply/bind to the returned curried
* function
* @returns {Function}
*/
function curry(func, context = null) {
return (...args) => args.length < func.length
? curry(func.bind(context, ...args))
: func.apply(context, args);
}
// An example of currying a simple function
function foo(one, two, three) {
bin.log(`${one} ${two} ${three}`);
}
const curriedFoo = curry(foo);
const things = [
'Sweet',
'Awesome',
'Amazing',
'JavaScript'
];
things.forEach(thing => foo('This', 'is', thing));
things.forEach(curriedFoo('This', 'is not so'));
foo('This', 'is', 'Normal');
curriedFoo('Wow')('Much Weird')('Very Parentheses');
// An example of externally currying a class method
class Baz {
constructor(name) {
this.name = name;
}
log(one, two, three) {
bin.log(`${one} ${this.name} ${two} ${three}`);
}
}
const cyclops = new Baz('Cyclops');
cyclops.log('This', 'is', 'one eyed');
cyclops.log = curry(cyclops.log, cyclops);
cyclops.log('This')('is talking to')('Nobody');
// An example of internally currying a class method
class Bar extends Baz {
constructor(name) {
super(name);
this.log = curry(this.log, this);
}
}
const actor = new Bar('Actor');
actor.log('This', 'is as', 'expected');
actor.log('This')('is super', 'Agile');
@Maximilianos
Copy link
Author

Maximilianos commented May 8, 2016

Currying a function in JS. Not a good thing in my opinion, but worth understanding how it works. I figured it out this weekend so sharing for whoever else might be interested 😄

http://www.webpackbin.com/EJxou5dWb
This bin should work.. but not sure.. so if it doesn't let me know.
(click on "main.js" to see the code and click on the "Log" button to see the log output)

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