javascript 28 lines · 7 steps

Building a curry function in JavaScript

A generic curry wrapper collects arguments across multiple calls until it has enough to invoke the original function.

Explained by highlit
1function curry(fn) {
2 return function curried(...args) {
3 if (args.length >= fn.length) {
4 return fn.apply(this, args);
5 }
6 return function (...rest) {
7 return curried.apply(this, args.concat(rest));
8 };
9 };
10}
11 
12const request = curry((method, baseUrl, path, options) =>
13 fetch(`${baseUrl}${path}`, { method, ...options })
14);
15 
16const api = request('GET', 'https://api.example.com');
17const getUser = api('/users');
18const getPost = api('/posts');
19 
20const log = curry((level, tag, message) =>
21 console[level](`[${tag}] ${message}`)
22);
23 
24const error = log('error');
25const dbError = error('db');
26const authError = error('auth');
27 
28export { curry, api, getUser, getPost, dbError, authError };
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Currying turns one multi-argument function into a chain of calls that each fix some arguments.
  2. 2Comparing collected arguments against `fn.length` lets curry decide when it finally has enough to run.
  3. 3Partially applying shared prefixes creates reusable, specialized functions from one generic definition.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a curry function in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code