Higher-order functions: pipe & once
Functions that take functions
Lesson 2 of 20 · 10 min · Module 1: Functions, deeper
map and filter accept functions as arguments. You can write your own functions that accept or return functions, and build small, reusable tools from them.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Pass functions as values
- Return new functions from functions
- Combine small functions into a pipeline
The idea
A higher-order function takes a function, returns one, or both. pipe(f, g, h) returns a function that runs f, passes the result to g, then to h. once(fn) returns a function that calls fn only the first time.
const twice = fn => x => fn(fn(x));
const addThree = x => x + 3;
console.log(twice(addThree)(10));
01Functions are values
You can store a function in a variable, put it in an array, or pass it to another function, exactly like a number or a string.
02Reduce over functions
pipe uses reduce: the accumulator is the current value, and each step applies the next function. The same pattern composes any number of steps.
const steps = [x => x + 1, x => x * 2];
console.log(steps.reduce((v, f) => f(v), 5));1203Use a flag, not the result
once stores whether it has been called separately from the result. Checking if (result) instead would call the function again whenever it returned 0, "" or false.
Your turn
pipe(...fns) that returns a function passing its argument through every function from left to right (with no functions, it returns the argument unchanged). Write once(fn) that returns a function which calls fn with its arguments the first time only and returns that first result on every later call.What the checks look for
- pipe applies functions from left to right
- pipe with no functions returns the input
- once calls the function only once and passes arguments
- once remembers a falsy first result
Take this with you
Higher-order functions turn small functions into reusable building blocks.
Go a little further
Write compose(...fns), which applies the functions from right to left, using reduceRight.