Monthly Archives: November 2016

JavaScript function compose + ES6 Spread , REST Operators

Below is sample for compose functions using older syntax (Minus ES6)

var add10 = function(x){
  return x + 10;
}

var multiply2 = function(x){
  return x * 2;
}

var square = function(x){
  return x*x;
}

var compose = function(){
  var funcs = arguments;
  return function(){
    var args = arguments;
    for(var count=0;count<funcs.length;count++){
      args = [funcs[count].apply(this, args)];
    }
    return args[0]
  }
}

var f = compose(add10, multiply2, square);
var result = f(10);
console.log(result);

Output is 1600

Now the same can be achieved using the ES6 Spread and REST operator

var add10 = function(x){
  return x + 10;
}

var multiply2 = function(x){
  return x * 2;
}

var square = function(x){
  return x*x;
}

var compose = function(...funcs){
  return function(...args){
    for(var count=0;count<funcs.length;count++){
      args = [funcs[count](...args)];
    }
    return args[0]
  }
}

var f = compose(add10, multiply2, square);
var result = f(10);
console.log(result);

 

REST operator – ES6 introduces the rest operator, three dots (…) that precede a named parameter. That parameter is now a rest parameter that is an Array containing the rest of the parameters, hence the name. Here is the use of REST parameters from the above e.g.

var compose = function(...funcs){
  return function(...args){
    return args[0]
  }
}

One rest parameter per function, there can only be one per function and it must be the last parameter declared in the function header. Attempting to have multiple rest parameters or putting one before other parameters will throw a SyntaxError.

Spread Operator: While rest parameters use the rest operator to combine zero or more parameters into a single array parameter, the spread operator does just the opposite. It separates an array into zero or more parameters.

The spread operator looks exactly like the rest operator. It is the same three dots (…). The only difference is that it is used in function calls and array literals instead of function parameter declarations. The spread operator should be able to replace the majority, if not all, uses of apply.

At first, using the spread operator may not seem like much of an improvement over apply, besides no longer having to specify undefined or this. However, the spread operator can be used anywhere in a function call and may be used more than once as well.

Below is the example for Spread Operator from the above compose sample

args = [funcs[count](...args)];

 

Advertisements