• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

214
Views
Function that supports both currying and traditional behaviour for 'n' parameters

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

about 3 years ago · Santiago Gelvez
1 answers
Answer question

0

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)());

about 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error