Skip to content

Commit 427c69c

Browse files
authored
Correct implementation of invert function
Fix invert function to correctly invert object key-value pairs.
1 parent e6ff252 commit 427c69c

1 file changed

Lines changed: 21 additions & 5 deletions

File tree

‎Sprint-2/interpret/invert.js‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,29 @@ function invert(obj) {
1717
}
1818

1919
// a) What is the current return value when invert is called with { a : 1 }
20-
20+
{ key: 1 }
2121
// b) What is the current return value when invert is called with { a: 1, b: 2 }
22-
22+
{ key: 2 }
2323
// c) What is the target return value when invert is called with {a : 1, b: 2}
24-
24+
{ "1": "a", "2": "b" }
2525
// c) What does Object.entries return? Why is it needed in this program?
26-
26+
Object.entries(obj) returns an array of key-value pairs as two-element arrays.
27+
Object.entries({ a: 1, b: 2 }) returns [["a", 1], ["b", 2]].
2728
// d) Explain why the current return value is different from the target output
28-
29+
The line invertedObj.key = value; contains bugs:
2930
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
31+
function invert(obj) {
32+
if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
33+
throw new TypeError("Expected a plain object");
34+
}
35+
36+
const invertedObj = {};
37+
38+
for (const [key, value] of Object.entries(obj)) {
39+
invertedObj[value] = key;
40+
}
41+
42+
return invertedObj;
43+
}
44+
45+
module.exports = invert;

0 commit comments

Comments
 (0)