Skip to content

Instantly share code, notes, and snippets.

@anthonybrown
Last active August 30, 2019 09:59
Show Gist options
  • Save anthonybrown/733cd667d6f42fb42bc335b9e1ef5c4e to your computer and use it in GitHub Desktop.
Save anthonybrown/733cd667d6f42fb42bc335b9e1ef5c4e to your computer and use it in GitHub Desktop.
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