array-first2

by shan10213223

JavaScript

var _ = {};
// _.first(array, [n])
// Returns an array with the first n elements of an array.
// If n is not provided it returns an array with just the first element.
_.first = function (array, n) {
  // if is not array
  if (!Array.isArray(array)) {
    return [];
  }
  // if n is null, zero, or negative
  if (n==null | n==0 | n<0) {
    return [array[0]];
  }
  
  // if n is greater than array length
  let boundry = n;
  if (n > array.length) {
    boundry = array.length;
  }
  return array.slice(0, boundry);

};

/*
let test1 = _.first([1,2,3], 2);
let test4 = _.first([1, 2, 3, 4, 5], 5);
let test2 = _.first([], 5);
let test3 = _.first([1,2,3], 5);
let test5 = _.first([1,2,3], -1)
console.log(test1, test2, test3, test4, test5);

console.log(typeof(_.first([1,2,3], 2)));
console.log([1,2,3].slice(0,2));
console.log(typeof([1,2,3].slice(0,2)));

console.log((_.first([1,2,3],2)) == ([1,2,3].slice(0,2)));
*/
let obj1 = [{name: 'jack', age: 14},  
            {name: 'jill', age: 15},  
            {name: 'humpty', age: 16}];

let test6 = _.first(obj1, 2);
let test7 = obj1.slice(0,2);

console.log(test6==test7);
console.log(typeof(test6) == typeof(test7));
console.log(test6.length == test7.length);