frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

455 - Curry with Placeholder - javascript

Open jsartisan opened this issue 2 months ago • 0 comments

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;
}

jsartisan avatar Sep 21 '25 15:09 jsartisan