ES 6 Spread Operators

by Preetha Srinivasan

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.4.1/chai.js"></script>
<div id="mocha"></div>

JavaScript

mocha.setup('bdd');

var expect = chai.expect;

describe('Spread operator tests', function() {

  it('Can be used to call a function', function() {
      const arr = [1, 2];
      const fn = (no1, no2) => {
        expect(arr[0]).to.equal(no1);
        expect(arr[1]).to.equal(no2);
      };
      fn(...arr); 
  });
  
  it('Can be used to find the max in an array',function(){
    const arr = [1, 2,3,4,5,6];
    expect(Math.max(...arr)).to.equal(6);
  });
  
  it ('Can be used to concat arrays',function(){
   const arr1= [1, 2,3,4,5,6];
   const arr2= [7,8,9,10];
   const arr3 = [...arr1,...arr2];
   expect(arr3.length).to.equal(10);
  });
  
  it ('Can be used to place an array at any point in another   array',function(){
     const arr1 = [5,6,7];
     const arr2 = [1,2,3,...arr1,8,9];
     expect(arr2.length).to.equal(8);
  });
  
  it('Can be used to copy arrays',function(){
    const arr1 = [1,2,3];
    const arr2 = [...arr1];
    expect(arr2.length).to.equal(3);
  });
  
  it('Can be used with dates',function(){
    const arr = [2015,1,1];
    const d = new Date(...arr);
    expect(new Date(2015,1,1).toString()).to.deep.equal(d.toString());
  })
  
});



mocha.run();