Some tips when using currying in Javascript

Curry in the right order

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));// Right order
const map = fn => array => array.map(fn)
const double = map(x => x * 2)
const increase3 = map(x => x + 3)
const result = compose(double, increase3)([20]) // result: 46// Wrong order, we cannot use it for composition
const map = array => fn => array.map(fn)

Flip a curried function

const map = array => fn => array.map(fn)const flippedMap = a => b => map(b)(a)

Add traceability to compose chain

const trace = label => x => {
console.log(label, x)
return x
}
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));const sum = a => b => a + b
const multiply = a => b => a * b
const addTransactionFee = sum(2)
const addTax = multiply(1.1)
const addMonthlyPromotion = multiply(0.8)
const paymentAmount = compose(
trace('addTransactionFee'),
addTransactionFee,
trace('addTax'),
addTax,
trace('addMonthlyPromotion'),
addMonthlyPromotion
)(100)
// Output:
// addMonthlyPromotion 80
// addTax 88
// addTransactionFee 90

Use pipe if you prefer reading in nature flow

const pipe = (...fns) => fns.reduceRight((f, g) => (...args) => f(g(...args)));const trace = label => x => {
console.log(label, x)
return x
}
const sum = a => b => a + b
const multiply = a => b => a * b
const addTransactionFee = sum(2)
const addTax = multiply(1.1)
const addMonthlyPromotion = multiply(0.8)
const paymentAmount = pipe(
trace('addTransactionFee'),
addTransactionFee,
trace('addTax'),
addTax,
trace('addMonthlyPromotion'),
addMonthlyPromotion
)(100)
// Output:
// addTransactionFee 100
// addTax 102
// addMonthlyPromotion 112.2

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store