Partial
JS Functions
Medium
15 min
closures
functional programming
Implement partial(func, ...boundArgs). It returns a function that calls func with boundArgs followed by whatever arguments it receives. Unlike Function.prototype.bind, it does not fix this, and it supports a placeholder (partial.placeholder) that leaves a position to be filled at call time.
const _ = partial.placeholder;
const greet = (greeting, name, punctuation) => `${greeting}, ${name}${punctuation}`;
const hello = partial(greet, 'Hello');
hello('Ada', '!'); // 'Hello, Ada!'
const askAda = partial(greet, _, 'Ada');
askAda('Hi', '?'); // 'Hi, Ada?' -> 'Hi' fills the hole, '?' is appended
Signature
partial(func: Function, ...boundArgs: any[]): Function
partial.placeholder: symbol
Requirements
- When the returned function is called, build the final argument list:
- Walk
boundArgs. Each placeholder is replaced by the next call argument, left to right. - Append any call arguments left over.
- If there are fewer call arguments than placeholders, the unfilled positions become
undefined.
- Walk
funcis always called on each invocation. Unlike currying, it never waits for more arguments.- The returned function forwards its own
thistofunc. - It is reusable: each call starts from the original
boundArgs.
Follow-up
- How would you implement
partialRight, which binds arguments to the end of the list? - Why can't
bindbe used here ifthisshould stay dynamic? - How does this differ from
curry?
Spotted a mistake or a rights concern? Report an issue