London | 26-ITP-May | Vito Moratti | Sprint 2 | Coursework - #1364
London | 26-ITP-May | Vito Moratti | Sprint 2 | Coursework#1364vmoratti wants to merge 18 commits into
Conversation
Add check for arrays in contains function
| // Given invalid parameters like an array | ||
| // When passed to contains | ||
| // Then it should return false or throw an error | ||
| test("contains an object returns true, or false otherwise", () => { | ||
| expect(contains([1, 2, 3, 'a'], "a")).toBe(false); | ||
| expect(contains([1, 2, 3, 'a'], "0")).toBe(false); | ||
| }); |
There was a problem hiding this comment.
Invalid parameters also include values like null, undefined, 1234, true. Could your function also return false when the first argument is one of these values?
There was a problem hiding this comment.
I have added extra validation to the contains() function now.
I believe it was not in the instruction, nor in the tests, that's why i didn't add them initially.
Refactor contains function to handle null, undefined, and Number types.
| module.exports = contains; | ||
| function contains(obj, prop) { | ||
| const notArray = !Array.isArray(obj); | ||
| if (obj === null || Array.isArray(obj) || obj === Number || obj === undefined) { |
There was a problem hiding this comment.
There are a few more non-object types that should also be rejected. Why not just reject any value that is an array or not an object?
Notes:
obj === Numberis not the correct syntax to check ifobjis a number or not.- Look up "How to check if a value is an object in JS"
cjyuan
left a comment
There was a problem hiding this comment.
Changes look good. Well done.
| return typeof value === 'object' | ||
| && value !== null | ||
| && !Array.isArray(value) | ||
| && !(value instanceof RegExp) | ||
| && !(value instanceof Date) | ||
| && !(value instanceof Set) | ||
| && !(value instanceof Map) |
There was a problem hiding this comment.
Note:
There are too many user-defined object types for us to exclude them all.
It's more important to know the trade-off and differences among the different approaches for checking if a value is an object in JavaScript.
Self checklist
Changelist
I attempted all tasks except the stretch