frontend-challenges
frontend-challenges copied to clipboard
455 - Curry with Placeholder - javascript
index.js
function curry(fn) {
function curried(...args) {
// If enough args and no placeholders → call fn
if (args.length >= fn.length && args.every(arg => arg !== __)) {
return fn(...args);
}
// Otherwise, return a function collecting more args
return (...nextArgs) => {
// merge args and nextArgs respecting placeholders
const merged = [];
let nextIndex = 0;
for (let arg of args) {
if (arg === __ && nextIndex < nextArgs.length) {
merged.push(nextArgs[nextIndex++]); // fill placeholder
} else {
merged.push(arg);
}
}
// leftover nextArgs
merged.push(...nextArgs.slice(nextIndex));
return curried(...merged);
}
}
return curried;
}