I am doing some exercises for a coding school and one of those is reimplementing _.first from Underline. My code is not passing one last test, which is "Should return an empty array if array is not an array", which should seem easy.
However, there is another test which is "Should work on an arguments object" and if I pass the second test, I cannot pass the first one and I cannot think of any other implementation atm. Here is my code for both of these tests:
function (array, n) {
let resultingArray = [];
let args = Array.prototype.slice.call(arguments, 0, 1);
let args2 = args[0];
if (!Array.isArray(array)) {
if (array.hasOwnProperty('length')) {
for (let key in args2) {
if (args2[key] == 'a' || args2[key] == 'b') {
resultingArray.push(args2[key]);
}
}
} else {
resultingArray = [];
}
} else if (array == undefined) {
resultingArray = [];
} else if (n == undefined || n <= 0) {
resultingArray = array.slice(0, 1);
} else {
resultingArray = array.slice(0, n);
}
return resultingArray;
};
The test gives me back the following:
should return an empty array if array is not an array ‣
TypeError: Cannot read property 'hasOwnProperty' of undefined
at Object._.first (index.js:14:15)
at Context.<anonymous> (test/test.js:34:9)_.first().should.eql([]);
_.first(null).should.eql([]);
_.first(1).should.eql([]);
Would appreciate any help on the subject, thanks in advance!
[].hasOwnProperty('length');istrueif (!Array.isArray(array))" doesn't make senseargsandargs2? AFAICS,args2 === array.