JS Spread Operator to normal form?

115 Views Asked by At

I have the following code that includes Spread Syntax in JS

const opposite = function (f) { return (function (...args) { return !f(...args) }) };

can it be converted without using Spread Syntax? It seems that if I do use this, some of the js minification tools fail to parse these lines of codes.

2

There are 2 best solutions below

0
slebetman On

You can by using the arguments object in combination with Function.prototype.apply():

The arguments object exist inside every function call and it represents the arguments to the function. Using this we can capture any and all arguments passed to the function.

The apply method on the other hand allow you to call a function by passing an array to represent the arguments.

Combining both we can do this:

const opposite = function (f) {
    return (function () {
        return !f.apply(null, arguments)
    })
};
0
Daniel Fleck On

would be to use the apply method, like this:

const opposite = function (f) { 
    return function () { 
        return !f.apply(this, arguments); 
    }
};

Another way to achieve the same result would be to use the call method and pass the arguments object to the function, like this:

const opposite = function (f) {
    return function () {
        return !f.call(this, ...arguments);
    }
};

Both of these methods allow you to pass an arbitrary number of arguments to the function without using the spread syntax.