Sub topic 11
Partial Application
This chapter assumes you know closures, higher-order functions, and the curry helper from the previous chapter. You should also be comfortable with rest and spread syntax.
Partial application means fixing some of a function's arguments now and getting back a new function that takes the remaining arguments later. Currying always turns a function into a chain of calls that each take one argument. Partial application is more direct: you choose which leading arguments to lock in, and the returned function takes everything else in a single call.
A General `partial` Helper
A closure is all you need. The returned function remembers the preset arguments and adds the later ones after them.
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const greet = (greeting, punctuation, name) =>
`${greeting}, ${name}${punctuation}`;
const hello = partial(greet, 'Hello', '!');
const welcome = partial(greet, 'Welcome');
console.log(hello('Ada')); // Hello, Ada!
console.log(welcome('?', 'Grace')); // Welcome, Grace?hello and welcome are specialized versions of greet. You don't need to write either of them by hand.
Built-in Partial Application with `bind`
Function.prototype.bind takes a value for this as its first argument, and any arguments after that are preset.
const multiply = (a, b) => a * b;
const double = multiply.bind(null, 2);
console.log(double(21)); // 42
console.log(double.length); // 1Notice that bind adjusts length to match the arguments that remain. The arrow-function partial above returns a function whose length is 0.
Argument Order Matters
Partial application can only fix arguments from the left. Put the arguments that change least often first, such as configuration, and put the data last. This ordering also lets partially applied functions work as callbacks:
const toInt = (radix, str) => parseInt(str, radix);
const parseDecimal = partial(toInt, 10);
console.log(['1', '2', '3'].map(parseInt)); // [ 1, NaN, NaN ]
console.log(['1', '2', '3'].map(parseDecimal)); // [ 1, 2, 3 ]map passes (value, index, array). Passing parseInt directly makes it treat the index as the radix. parseDecimal has the radix fixed at 10, so toInt uses only str and the extra arguments do nothing.
Partial Application vs. Currying
| Aspect | Partial application | Currying |
|---|---|---|
| Result | One function taking all remaining arguments | A chain of functions until arity is met |
| Number of steps | You fix arguments once | Each call can supply more arguments |
| Depends on `fn.length` | No | Yes |
| Built-in support | `bind` | None |
Common Errors
- Using
bindon methods carelessly. The first argument becomesthis. If you passnullto a method that readsthis, it breaks. Arrow functions ignore the boundthisentirely. - Currying a partially applied function. The
partialhelper returns a function withlength0. If you pass that function tocurry,currycalls it right away with no arguments. - Wrong argument order. If the value you want to fix comes last, wrap the function in an arrow function instead, for example
(x) => fn(x, fixed).
Exercise
Using the partial helper, create logWarn from log = (level, tag, msg) => [${level}] ${tag}: ${msg} so that logWarn('db', 'slow query') returns "[WARN] db: slow query". What does logWarn.length return, and what would it return if you used bind instead?
Show answer
const logWarn = partial(log, 'WARN'); logWarn('db', 'slow query') returns "[WARN] db: slow query". logWarn.length is 0 because the returned arrow function uses only a rest parameter. With log.bind(null, 'WARN'), length is 2, because bind subtracts the preset arguments from the original arity of 3.
Exercise
Why does ['10', '10', '10'].map(parseInt) return [10, NaN, 2], and how does partial application fix it?
Show answer
map calls parseInt(value, index), so the radixes are 0 (treated as 10), 1 (invalid, so NaN), and 2 ('10' in binary is 2). Fixing the radix with partial(toInt, 10), where toInt = (radix, str) => parseInt(str, radix), means the index map passes as an extra argument is ignored.