Skip to content

Instantly share code, notes, and snippets.

@iHani
Last active August 4, 2018 22:56
Show Gist options
  • Save iHani/5f360694ffdb17e4f5b0f2a34d773127 to your computer and use it in GitHub Desktop.
Save iHani/5f360694ffdb17e4f5b0f2a34d773127 to your computer and use it in GitHub Desktop.
Currying (also partial application)
function person (name) {
return function age (age) {
return `${name} is ${age}`
}
}
// if we called
const arg1 = 'Richard'
const arg2 = 30
console.log(person(arg1)(arg2))
// Richard is 30
////////
// We can also do
function driver (name) {
return function age (age) {
return function car (car) {
return `${name} is ${age} and drives ${car}`
}
}
}
const drives = driver(arg1)(arg2)
console.log(drives('Toyota'))
// Richard is 30 and drives Toyota
// OR
const drives = driver(arg1)
console.log(drives(arg2)('Toyota'))
// Richard is 30 and drives Toyota
// same as above, order of passed argument will
// be carried down to the next returned function
////////
// passing two arguments in some curried functinos
function person2 (name) {
return function age (age) {
return function car (car, year) {
return `${name} is ${age} and drives ${car} ${year}`
}
}
}
const drives = person2(arg1)(arg2)
console.log(drives('Toyota', 1997))
// Richard is 30 and drives Toyota 1997
////////
// more currying level
function person2 (name) {
return function age (age) {
return function car (car, year) {
return function condition (cond) {
return `${name} is ${age} and drives ${car} ${year} ${cond}`
}
}
}
}
const condition = 'New'
const drives = person2(arg1)(arg2)
console.log(drives('Toyota', 1997)(condition))
// Richard is 30 and drives Toyota 1997 New
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment