'Function that supports both currying and traditional behaviour for 'n' parameters [duplicate]

I have the below code wherein, I have wrapped functions to achieve the above behaviour. But unfortunately it returns expected result only when the no of parameters equals to 2.

function baseCurry (func) {
    return function (...args) {
      if (args.length >= func.length) {
        return func.call(this, ...args)
      } else {
        return baseCurry(func.bind(this, ...args))
      }
    }
  }
  
  function addHelper (x, y) {
    return x + y;
  }
  
  const superCurry = baseCurry(addHelper);

Test Cases:

  console.log(superCurry(1, 5)); // 6
  console.log(superCurry(1)(5)); // 6
  console.log(superCurry(1)); // [Function (anonymous)]
  console.log(superCurry(1)(2)(3)); // Error
  console.log(superCurry(1,2)(3)); // Error

I need to change it in such a way that it gives expected result for all n >= 1, where 'n' is the number of parameters

Note:

The params can be passed in any combinations like

console.log(superCurry(1,2)(3)(4))
console.log(superCurry(1,2,3)(5,7)(4)(8,9))

Thanks in advance



Solution 1:[1]

I could do something similar to your expectation, but I do need an extra pair of () at the end of the call chain so that the function will know when a function is to be returned and when the value.

function baseCurry (func, value) {
    this.value = value ?? 0;
    return (...args) => {
      if (args.length === 0) {
          let val = this.value;
          this.value = 0;
          return val;
      }
      for (let index = 0; index < args.length; index += func.length - 1) {
          this.value = func(this.value, ...args.slice(index, (index + func.length - 1 <= args.length) ? index + func.length - 1 : undefined));
      }
      return baseCurry(func, this.value);
    }
  }
  
  function addHelper (x, y) {
    return x + y;
  }
  
  const superCurry = baseCurry(addHelper);

  console.log(superCurry(1, 5)());
  console.log(superCurry(1)(5)());
  console.log(superCurry(1)());
  console.log(superCurry(1)(2)(3)());
  console.log(superCurry(1,2)(3)());
  console.log(superCurry(1,2,3)());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lajos Arpad