Return last n items

Here is my code not sure whats up, wants me to return the last n items of an array

function getLastItems(array, n) {
  var arr1 = []
  var arr2 = array.reverse()
  for(i=0;i<n;i++)
  {
    arr1.push(arr2[i])
 
  }
  
  return arr1.reverse()
 
 
   // return an array with the first 'n'  items of 'array'
}

here is what the program tests against


 describe('getLastItems', () => {
    it('returns an array with the n last items of the passed array', () => {
      const array = ['a', 2, true, 4, null];
      expect(getLastItems(array, 1)).to.eql([null]);
      expect(getLastItems(array, 3)).to.eql([true, 4, null]);
      expect(getLastItems(array, 5)).to.eql(array);
    });
  });

Im getting the following result tho when I run it via npm

getLastItems
      1) returns an array with the n last items of the passed array


  50 passing (57ms)
  1 failing

  1) arrays
       getLastItems
         returns an array with the n last items of the passed array:

      AssertionError: expected [ true, 2, 'a' ] to deeply equal [ true, 4, null ]
      + expected - actual

       [
         true
      -  2
      -  "a"
      +  4
      +  [null]
       ]

      at Context.it (test/4-arrays.test.js:78:41)



npm ERR! Test failed.  See above for more details.

array.reverse mutates the array. Also, arrays and objects get passed as a reference to the original.

Take a look at the assertions. They all happen inside the same block, so the original array gets mutated between calls.

describe('getLastItems', () => {
    it('returns an array with the n last items of the passed array', () => {
      const array = ['a', 2, true, 4, null];
     
     /* 
     * receives [ 'a', 2, true, 4, null ] 
     */
      expect(getLastItems(array, 1)).to.eql([null]);

     /* 
     * but since array.reverse was called,
     * this receives [ null, 4, true, 2, 'a' ] 
     * AssertionError: expected [ true, 2, 'a' ] to deeply equal [ true, 4, null ]
     */
      expect(getLastItems(array, 3)).to.eql([true, 4, null]); 
      expect(getLastItems(array, 5)).to.eql(array);
    });
  });

There are two ways to guard against this

function getLastItems(array, n) {
  var arr1 = []
  var arr2 = array.reverse()
 /* ... */
  
  // reset the original array
  array.reverse()
  return arr1.reverse()
 
 
   // return an array with the first 'n'  items of 'array'
}

  1. use an immutable array method