Skip to content

Instantly share code, notes, and snippets.

@anthonybrown
Last active Aug 30, 2019
Embed
What would you like to do?
A simple example of currying in functional JavaScript
function greetCurried(greeting) {
return function(name) {
if (typeof(greeting) !== 'string') {
return ('Greetings!')
} else if (typeof(name) !== 'string') {
return (greeting)
}
return (`${greeting}, ${name}`)
}
}
const greetHello = greetCurried("Hello");
console.log(greetHello('Helen'));
console.log(greetHello(5));
// now it's easy to create a set of functions that share related
// code but provide custom functionality
const greetHi = greetCurried("Hi");
console.log(greetHi('Debbie'));
console.log(greetHi(5));
const greetHowdy = greetCurried("Howdy");
console.log(greetHowdy('Klaudia'));
console.log(greetHowdy(5));
// the curried function even prevents us from creating broken
// versions that incorporate an incorrect type.
const greetWrongType = greetCurried(5)
console.log(greetWrongType('Joey'));
console.log(greetWrongType(5));
console.log(greetWrongType(null));
console.log(greetWrongType(undefined));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment