attempting to create a function that will return an array with the first n elements of a given array. It must have the following handling:
- should return an array with the first n elements of the array
- should return an array with the first element if n is not a number, is zero, or negative
- should return the entire array if n is > length
- should work on an arguments object
- should return an empty array if array is not an array
I'm having trouble satisfying the "should work on an arguments object" while using the following code. When I add a line of code to convert the arguments object into an array then it raises an error with "should return an empty array if array is not an array" - because we're automatically converting the argument into an array. Thank you in advance for any help.
_.first = function (array, n) {
array = Array.from(array);
if (!Array.isArray(array)) return [];
if (isNaN(n) || n <= 0) return [array[0]];
if (array.length - 1 < n) return array;
return array.slice(0, n);
};
Via Active questions tagged javascript - Stack Overflow https://ift.tt/rbUlWxp
Comments
Post a Comment