JavaScript Currying 4 - Trace

September 17, 202014 min read

Function composition using point-free style creates a very concise and readable code:

const trace = (label) => (value) => {
console.log(`${label}: ${value}`)
return value
}
const compose = (...functions) => (x) =>
functions.reduceRight((y, f) => f(y), x)
const g = (n) => n + 1
const f = (n) => n * 2
const h = compose(
trace('after f'), // 'after f: 42'
f,
trace('after g'), // 'after g: 21'
g
) // function application order is from bottom to top
h(20) // => 42

Compose can be a fantastic, utility, but a more convenient way of reading code is top-to-bottom:

const trace = (label) => (value) => {
console.log(`${label}: ${value}`)
return value
}
const g = (n) => n + 1
const f = (n) => n * 2
const pipe = (...functions) => (x) => functions.reduce((y, f) => f(y), x)
// updated usage
const h = pipe(
g,
trace('after g'), // 'after g: 21'
f,
trace('after f') // 'after f: 42'
) // function application order is from top to bottom
h(20) // => 42

Currying can be a useful abstraction to specialized functions:

const map = (fn) => (mappable) => mappable.map(fn)
const double = (n) => n * 2
const doubleAll = map(double)
doubleAll([1, 2, 3]) // => [2, 4, 6]

If the trace function were not curried, it would look like this:

const g = (n) => n + 1
const f = (n) => n * 2
const pipe = (...functions) => (x) => functions.reduce((y, f) => f(y), x)
const trace = (label, value) => {
console.log(`${label}: ${value}`)
return value
}
const h = pipe(
g,
(x) => trace('after g', x), // 'after g: 21'
f,
(x) => trace('after f', x) // 'after f: 42'
)
h(20) // => 42

Data the last style means that function should take the specializing parameters first and take the data later.

The arguments which have been applied to partially applied function are called fixed parameters.

Point-free style is a way of defining function without reference to its arguments. Point free function is created by calling a function that returns a function such as a curried function.