Skip to content

Instantly share code, notes, and snippets.

@Sysetup
Created October 12, 2016 19:57
Show Gist options
  • Select an option

  • Save Sysetup/11fdf7ef32f6f32b11d7e2cc338cde55 to your computer and use it in GitHub Desktop.

Select an option

Save Sysetup/11fdf7ef32f6f32b11d7e2cc338cde55 to your computer and use it in GitHub Desktop.
Currying in Functional JavaScript.
var greetCurried = function(greeting) {
return function(name) {
console.log(greeting + ", " + name);
};
};
var greetHello = greetCurried("Hello");
//console.log('greetHello: ' + greetHello());
greetHello("Heidi"); //"Hello, Heidi"
greetHello("Eddie"); //"Hello, Eddie"
greetCurried("Hi there")("Howard"); //"Hi there, Howard"
///
console.log('\n');
var greetDeeplyCurried = function(greeting) {
return function(separator) {
return function(emphasis) {
return function(name) {
console.log(greeting + separator + name + emphasis);
};
};
};
};
var greetAwkwardly = greetDeeplyCurried("Hello")("...")("?");
greetAwkwardly("Heidi"); //"Hello...Heidi?"
greetAwkwardly("Eddie"); //"Hello...Eddie?"
//--
greetDeeplyCurried("Hello")("...")("?")("Carlos");
//--
var sayHello = greetDeeplyCurried("Hello")(", ");
sayHello(".")("Heidi"); //"Hello, Heidi."
sayHello(".")("Eddie"); //"Hello, Eddie."
//--
var askHello = sayHello("?");
askHello("Heidi"); //"Hello, Heidi?"
askHello("Eddie"); //"Hello, Eddie?"
///
console.log('\n');
var curryIt = function(uncurried) {
var parameters = Array.prototype.slice.call(arguments, 1);
return function() {
return uncurried.apply(this, parameters.concat(
Array.prototype.slice.call(arguments, 0)
));
};
};
var greeter = function(greeting, separator, emphasis, name) {
console.log(greeting + separator + name + emphasis);
};
var greetHello = curryIt(greeter, "Hello", ", ", ".");
greetHello("Heidi"); //"Hello, Heidi."
greetHello("Eddie"); //"Hello, Eddie."
var greetGoodbye = curryIt(greeter, "Goodbye", ", ");
greetGoodbye(".", "Joe"); //"Goodbye, Joe."
//https://www.sitepoint.com/currying-in-functional-javascript/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment