Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Currying and Partial Application. Composition made easier.
// Helper functions
const compose = (...fns) => x =>
fns.reduceRight((y, f) => f(y), x)
const curry = (fn, n) => {
const arity = n || fn.length
return (...params) =>
params.length >= arity
? fn(...params)
: curry(
(...rest) => fn(...params, ...rest),
arity - params.length
)
}
const log = curry((label, value) => {
console.log(`[${label}]`, value)
return value
})
const prop = curry((name, obj) =>
obj[name]
)
// Array functions
const map = curry((mapper, list) =>
list.map(mapper)
)
const filter = curry((predicate, list) =>
list.filter(predicate)
)
const reduce = curry((reducer, initial, list) =>
list.reduce(reducer, initial)
)
// Domain functions
const add = curry((x, y) =>
x + y
)
const isAdmin = prop('admin')
const getAge = prop('age')
const sum = reduce(add, 0)
const sumAdminAges = compose(
sum,
log('Ages'),
map(getAge),
log('Admin users'),
filter(isAdmin),
log('List of users')
)
// execution
const users = [
{ admin: true, age: 30 },
{ admin: false, age: 45 },
{ admin: true, age: 40 },
{ admin: false, age: 80 },
]
sumAdminAges(users)
// [List of users] [ { admin: true, age: 30 },
// { admin: false, age: 45 },
// { admin: true, age: 40 },
// { admin: false, age: 80 } ]
// [Admin users] [ { admin: true, age: 30 }, { admin: true, age: 40 } ]
// [Ages] [ 30, 40 ]
// 70
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.