For an exercise, I have to reproduce the first function from the Underscore.js library.
The code I wrote passes all the tests, except "should work on an arguments object".
I passed these tests:
- 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 return an empty array if array is not an array
I failed this test: should work on an arguments object
_.first = function (array, n) {
let arr = [];
if (!Array.isArray(array)) {
return [];
} else if (isNaN(n) || n == null || n <= 0) {
return [array[0]];
} else {
for (let i = 0; i < n && i < array.length; i++) {
arr.push(array[i]);
}
}
return arr;
};
I would be happy to get some guidance to understand why I am failing to pass the arguments object test. Thanks!
Edit: the solution to my problem:
function (array, n) {
let arr = [];
if (
!(
Array.isArray(array) ||
Object.prototype.toString.call(array) === "[object Arguments]"
)
) {
return [];
}
if (isNaN(n) || n == null || n <= 0) {
return [array[0]];
} else {
for (let i = 0; i < n && i < array.length; i++) {
arr.push(array[i]);
}
}
return arr;
};