JS Built-ins
← Array155 / 226
ArrayArray.prototype.reduceRightadvanced

Array.prototype.reduceRight() β€” function composition

πŸ“– Usage Example
const double = x => x * 2
const addOne = x => x + 1
const fns = [double, addOne]
fns.reduceRight((v, fn) => fn(v), 3)
// addOne(double(3)) β†’ 7

Use reduceRight() to compose functions right-to-left, applying each to the accumulated result.

Function composition with reduceRight

In functional programming, compose applies functions right-to-left. reduceRight() is a natural fit.

const double = (x: number) => x * 2
const addOne = (x: number) => x + 1
compose([addOne, double])(3) // addOne(double(3)) = addOne(6) = 7
πŸ’‘ Hints (3)
  • β€’ Return a new function `(x) => fns.reduceRight(...)` so the composed function is reusable.
  • β€’ Pass `x` as the initial accumulator value to `reduceRight`.
  • β€’ The rightmost function in the array is applied first to the input.