Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

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 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda