<div id="root"></div>
// this is just here to display results to DOM
const addResultToDOM = (...args) => $('#root').append(`<div>${args.join(' ')}</div>`)
const compose = (...fns) => arg => fns.reduce((acc, fn) => fn(acc), arg)
const curry = (uncurriedFn, ...args) => {
// you can get the arity of a function by calling length on the fn
const arity = uncurriedFn.length
const accumulator = (...accArgs) => {
let argsCopy = [...args] //
if (accArgs.length > 0) {
argsCopy = [...argsCopy, ...accArgs]
}
if (args.length >= arity) return uncurriedFn.apply(null, argsCopy)
return curry.apply(null, [uncurriedFn, ...argsCopy]) // recurse
}
// if any args passed in, pass them to the accumulator
return args.length >= arity ? accumulator() : accumulator
}
const add = x => y => x + y
const subtract = x => y => y - x
const multiply = x => y => x * y
const divide = x => y => y / x
const sum = (x, y, z) => x + y + z
const [
curriedAdd,
curriedSubtract,
curriedMultiply,
curriedDivide,
curriedSum
] = [
add,
subtract,
multiply,
divide,
sum
].map(i => curry(i)) // this simply creates curried versions of our functions
addResultToDOM('results of compose(curriedAdd(5), curriedSubtract(1), curriedMultiply(4), curriedDivide(2), curriedSum(3, 4))(1):', compose(curriedAdd(5), curriedSubtract(1), curriedMultiply(4), curriedDivide(2), curriedSum(3, 4))(1))
This Pen doesn't use any external CSS resources.