Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active May 11, 2020 20:44
Show Gist options
  • Save nathansmith/913311f95e8a7596b13d to your computer and use it in GitHub Desktop.
Save nathansmith/913311f95e8a7596b13d to your computer and use it in GitHub Desktop.
Basic examples of currying in JavaScript.
// Our currying wrapper.
function superSuit (a) {
return function (b) {
return 'I can now ' + b + ' like ' + a + '.';
}
}
// Get the suit ready.
var ironman = superSuit('Iron Man');
// "I can now punch like Iron Man."
ironman('punch');
// "I can now fly like Iron Man."
ironman('fly');
/*
Or, chain directly...
*/
// "I can now use cool gadgets like Batman."
superSuit('Batman')('use cool gadgets');
// "I can now complain about Krypton like Superman."
superSuit('Superman')('complain about Krypton');
// Our currying wrapper.
function eatTogether (a) {
return function (b) {
return 'I eat ' + b + ' with ' + a + '.';
}
}
// Get the cheese ready.
var cheese = eatTogether('cheese');
// "I eat broccoli with cheese."
cheese('broccoli');
// "I eat ham with cheese."
cheese('ham');
/*
Or, chain directly...
*/
// "I eat pie with ice cream."
eatTogether('ice cream')('pie');
// "I eat peanut butter with jelly."
eatTogether('jelly')('peanut butter');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment