3
function partialize(){

}

function calculation(a,b,c){
  console.log(a*b/c);
  return a*b/c;
}

var a = 10, b= 20, c= 5;

var partialize1 = partialize(calculation, a);
partialize1(b,c)

var partialize2 = partialize(calculation, a, b);
partialize2(c)

var partialize3 = partialize(calculation, a, b, c);
partialize3()

I need to write partialize function which give same output in all three condition.

I tried like that it work .but i used spread operator .can we do this without spread operator ?

 function partialize(fn,...a) {
    console.log(...a);

    return function (...b) {
        console.log(...b);
        fn(...a,...b);

    }

}

function calculation(a, b, c) {
    console.log(a * b / c);
    return a * b / c;
}

var a = 10, b = 20, c = 5;

var partialize1 = partialize(calculation, a);
partialize1(b, c)

var partialize2 = partialize(calculation, a, b);
partialize2(c)

var partialize3 = partialize(calculation, a, b, c);
partialize3()

can we do the same thing without spread operator ?

user944513
  • 12,247
  • 49
  • 168
  • 318

3 Answers3

3

You can save the initial arguments that were passed and return a function that can be called with the rest of the arguments, then calling the original function with apply:

function partialize(fn) {
  const initialArguments = Array.from(arguments).slice(1);
  return function() {
    const finalArguments = Array.from(arguments);
    fn.apply(null, initialArguments.concat(finalArguments));
  }
}

function calculation(a, b, c) {
  console.log(a * b / c);
  return a * b / c;
}

var a = 10,
  b = 20,
  c = 5;

var partialize1 = partialize(calculation, a);
partialize1(b, c)

var partialize2 = partialize(calculation, a, b);
partialize2(c)

var partialize3 = partialize(calculation, a, b, c);
partialize3()
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

If your code is currently working as is but you'd like to change it to not use the spread operator, you can use the arguments object instead.

arguments object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

Also check out this stackoverflow question for some example code working with the arguments object if helpful. How can I convert the "arguments" object to an array in JavaScript?

kyle
  • 691
  • 1
  • 7
  • 17
  • Beat me by a few seconds on this answer. I don't see what's wrong with using spread, but `arguments` is the only reasonable options otherwise. – ajxs Jun 21 '18 at 23:57
0

user944513, to simulate an overload of methods in javascript, yo can use the arguments object, which comes by default in the functions. To explain you better, i've written a block of code. Hope this can help you:

function suma(a = 0){

let resultado = 0;

console.log(arguments.length);

for(let i = 0; i < arguments.length; i++)
{

if(typeof(arguments[i] == "number")){
  resultado += arguments[i];
}
}
}

suma(1,2,3,4); // 10

suma(1,2) // 3