Manchester | 26-ITP-May | Joanne O'Malley | Sprint 2 | Exercises#1247
Manchester | 26-ITP-May | Joanne O'Malley | Sprint 2 | Exercises#1247joanne342 wants to merge 21 commits into
Conversation
LonMcGregor
left a comment
There was a problem hiding this comment.
Good start on this task, I've left some comments for you to answer
| @@ -1,3 +1,5 @@ | |||
| function contains() {} | |||
| function contains(obj, property_name) { | |||
| return property_name in obj; | |||
There was a problem hiding this comment.
Does this consider the difference between defined properties and built-in properties?
There was a problem hiding this comment.
Hello
I changed
return property_name in obj;
to
return Object.prototype.hasOwnProperty.call(obj, property_name);
and added the test case
test("returns false for inherited properties like toString", () => {
expect(contains({}, "toString")).toBe(false);
});
to illustrate the difference.
| const splitByAnds = queryString.split("&"); | ||
|
|
||
| const splitByEquals = splitByAnds.map(x => { | ||
| const match = x.match(/^([^=]*)(?:=(.*))?$/); |
There was a problem hiding this comment.
Can you explain what this regular expression is doing?
There was a problem hiding this comment.
([^=]*)
Make a capturing group of zero or more characters that are not =, grabbing as many as possible until the first equals sign (if one exists).
===
(?:=(.*))?
The second capturing group (.*) grabs everything after the first equals sign, including any additional equals signs. It is wrapped in a non-capturing group (?:...) because we don't want the = part itself to create another capture group.
===
It functions similarly to .split("=") with a limit of one split. A normal .split("=") does not work here because query values can themselves contain equals signs. For example, equation=a=b-2 should become:
["equation", "a=b-2"]
rather than:
["equation", "a", "b-2"]
In Python this is equivalent to:
"equation=a=b-2".split("=", 1)
|
|
||
| const counts = {}; | ||
| for (const item of uniqueItems) { | ||
| counts[item] = items.filter(x => x === item).length; |
There was a problem hiding this comment.
Imagine I had the input of ['a', 'a', 'a', ...] - How many times will .filter run? Is that an optimal solution?
There was a problem hiding this comment.
The current solution loops through the array once to build the unique list, then runs .filter() for each unique item.
If the array contains only duplicates like ['a', 'a', 'a'], the set reduces it to ['a'], so .filter() only runs once. This gives us O(n).
If every item is unique, .filter() runs once for every item in the array, and each filter scans the whole array again. This gives us O(n²).
A more efficient approach is to loop through the array once and store the counts as we go using an object or dictionary.
Learners, PR Template
Self checklist
Changelist
Sprint 2 coursework