Skip to content

Commit b45be0a

Browse files
committed
invert key with value and test
1 parent fab29c2 commit b45be0a

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

Sprint-2/interpret/invert.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,34 @@ function invert(obj) {
1010
const invertedObj = {};
1111

1212
for (const [key, value] of Object.entries(obj)) {
13-
invertedObj.key = value;
13+
invertedObj[value] = key;
1414
}
1515

1616
return invertedObj;
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+
//{"1": "a", "2": "b"}
2425

2526
// c) What does Object.entries return? Why is it needed in this program?
26-
27+
// Object.entries gives an array of [key, value] pairs.
2728
// d) Explain why the current return value is different from the target output
28-
29+
// invertedObj.key sets a property literally called "key". We need to use the variable key as the dynamic property name. and we need to change "key" to "value" and "value" to "key".
2930
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
31+
console.assert(
32+
JSON.stringify(invert({ a: 1, b: 2 })) === JSON.stringify({ "1": "a", "2": "b" }),
33+
"multiple keys test failed"
34+
);
35+
console.assert(
36+
JSON.stringify(invert({ x: "hello", y: "world" })) === JSON.stringify({ "hello": "x", "world": "y" }),
37+
"string cases test failed"
38+
);
39+
console.assert(
40+
JSON.stringify(invert({})) === JSON.stringify({}),
41+
"empty test failed"
42+
);
43+
console.log("All tests passed!");

0 commit comments

Comments
 (0)