Skip to content

Commit 61cbfbb

Browse files
committed
fix: correct implementation of invert function to properly swap keys and values
1 parent 2438407 commit 61cbfbb

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

Sprint-2/interpret/invert.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,30 @@
99
function invert(obj) {
1010
const invertedObj = {};
1111

12+
// Checked for non-object input (optional, but robust)
13+
if (typeof obj !== "object" || obj === null) {
14+
return invertedObj;
15+
}
16+
1217
for (const [key, value] of Object.entries(obj)) {
13-
invertedObj.key = value;
18+
// Used bracket notation to dynamically set the value as the new key,
19+
// and assign the original key as the new value.
20+
invertedObj[value] = key;
1421
}
1522

1623
return invertedObj;
1724
}
18-
25+
/*
1926
// a) What is the current return value when invert is called with { a : 1 }
20-
27+
invert({ a: 1 }); // returns: { key: 1 }
2128
// b) What is the current return value when invert is called with { a: 1, b: 2 }
22-
29+
invert({ a: 1, b: 2 }); // returns: { key: 2 }
2330
// c) What is the target return value when invert is called with {a : 1, b: 2}
24-
31+
{ "1": "a", "2": "b" }
2532
// c) What does Object.entries return? Why is it needed in this program?
26-
33+
Object.entries({ a: 1, b: 2 }) // returns: [["a", 1], ["b", 2]]
34+
//Each entry is a [key, value] pair. Needed because we want to iterate over keys and values simultaneously in a for...of loop.
2735
// d) Explain why the current return value is different from the target output
28-
36+
// Because you wrote invertedObj.key instead of using the dynamic key from the variable value. invertedObj.key creates a property literally named "key", not the value of the variable key.
2937
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
38+
*/

0 commit comments

Comments
 (0)