Reputation: 1458
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!
Upvotes: 0
Views: 151
Reputation: 7305
The reason the problem exists, is because you aren't checking if array
is null
or undefined
before using it as an object in array.hasOwnProperty('length')
. Doing the change shown below should fix the problem.
(array.hasOwnProperty('length'))
=> (array != null && array.hasOwnProperty('length'))
Note that !=
is used rather than !==
so that both null
and undefined
will get checked. If you only want to loop through an Object, then you can instead use this check typeof array === "object"
.
Finally, I would recommend using typeof array[Symbol.iterator] === "function"
instead of array.hasOwnProperty('length')
. To see if the property can actually be looped for, rather than checking if it has a length
property. (This is assuming that you are using ES6 though, since symbols don't exist in ES5)
Upvotes: 1