You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 75ce6cb
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: Sprint-2/interpret/invert.js
+41-4Lines changed: 41 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -5,6 +5,7 @@
5
5
// Then it should swap the keys and values in the object
6
6
7
7
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
8
+
/*
8
9
9
10
function invert(obj) {
10
11
const invertedObj = {};
@@ -15,15 +16,51 @@ function invert(obj) {
15
16
16
17
return invertedObj;
17
18
}
19
+
*/
20
+
/* a) What is the current return value when invert is called with { a : 1 }
18
21
19
-
// a) What is the current return value when invert is called with { a : 1 }
22
+
{ key: 1 }
20
23
21
24
// b) What is the current return value when invert is called with { a: 1, b: 2 }
22
25
26
+
{ key: 2 }
23
27
// c) What is the target return value when invert is called with {a : 1, b: 2}
24
28
25
-
// c) What does Object.entries return? Why is it needed in this program?
29
+
{ "1": "a", "2": "b" }
30
+
// d) What does Object.entries return? Why is it needed in this program?
26
31
27
-
// d) Explain why the current return value is different from the target output
32
+
Object.entries(obj) returns an array of an object's own key-value pairs as [key, value] tuples (e.g., Object.entries({ a: 1, b: 2 }) returns [['a', 1], ['b', 2]]).
28
33
29
-
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
34
+
It is needed here so we can loop over both the property name (key) and its corresponding value (value) at the same time using array destructuring (const [key, value]).
35
+
36
+
// e) Explain why the current return value is different from the target output
37
+
38
+
There are two critical issues in the current loop
39
+
1. Static property assignment instead of dynamic lookup;
40
+
The code writes invertedObj.key = value. Using dot notation literally creates/overwrites a single key named "key" on the object every single iteration.
41
+
To use the variable's value dynamically as the object key, you must use bracket notation: invertedObj[value].
42
+
43
+
2. Flipped key and value;
44
+
The target output asks to swap keys and values (so values become keys and keys become values). The original code assigns value to the object's key position,
45
+
rather than assigning key to the position indexed by value (invertedObj[value] = key). */
46
+
47
+
// f) Fix the implementation of invert (and write tests to prove it's fixed!)
0 commit comments