Curry Functions With Placeholders
Transform multi-argument functions into curried variants that support placeholders and partial application.
Code
export const curryPlaceholder = Symbol("curry.placeholder");
export function curry(fn, arity = fn.length) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(arity) || arity < 0) throw new RangeError("arity must be a non-negative integer");
return function curried(...args) {
const supplied = args.slice(0, arity);
if (supplied.length === arity && !supplied.includes(curryPlaceholder)) {
return fn.apply(this, supplied);
}
return function next(...more) {
const merged = [];
let cursor = 0;
for (const argument of args) {
if (argument === curryPlaceholder && cursor < more.length) {
merged.push(more[cursor]);
cursor += 1;
} else {
merged.push(argument);
}
}
while (cursor < more.length) {
merged.push(more[cursor]);
cursor += 1;
}
return curried.apply(this, merged);
};
};
}
export function uncurry(curried) {
if (typeof curried !== "function") throw new TypeError("curried must be a function");
return (...args) => args.reduce((fn, argument) => fn(argument), curried);
}What the code does
Curry Functions With Placeholders keeps everything in the functions curry, curried, next and uncurry.
Iteration is nested: for (const argument of args) frames the pass, while (cursor < more.length) does the per-item step. TypeError and RangeError is the guard’s signal — thrown at the branch, before any partial work happens.
Caveats
- The guard
typeof fn !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads export const curryPlaceholder =
curryPlaceholder is the public entry point; everything else in the file exists to support it.
Statements that matter
return (...args) => args.reduce((fn, argument) => fn(argument), curried);
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(arity) || arity < 0) throw new RangeError("arity must be a non-negative integer");
Interactive Tools for This Topic
FAQ
- How does the code behave when input is bad?
- `TypeError` and `RangeError` is raised at the guard (`typeof fn !== "function"`), so invalid state never reaches the main logic.
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `curry`, `curried`, `next` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.