Skip to content

Commit 03c6296

Browse files
committed
Fix invert function and add tests for key-value swapping
1 parent 5ee5409 commit 03c6296

2 files changed

Lines changed: 38 additions & 5 deletions

File tree

‎Sprint-2/interpret/invert.js‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
// Then it should swap the keys and values in the object
66

77
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
8-
8+
/*
99
function invert(obj) {
1010
const invertedObj = {};
1111
@@ -15,15 +15,31 @@ function invert(obj) {
1515
1616
return invertedObj;
1717
}
18+
*/
1819

19-
// a) What is the current return value when invert is called with { a : 1 }
20+
// a) What is the current return value when invert is called with { a : 1 } - The current return value is { key: 1}
2021

21-
// b) What is the current return value when invert is called with { a: 1, b: 2 }
22+
// b) What is the current return value when invert is called with { a: 1, b: 2 } - The current return value is { key: 2}
2223

23-
// c) What is the target return value when invert is called with {a : 1, b: 2}
24+
// c) What is the target return value when invert is called with {a : 1, b: 2} - The target return value is { "1": "a", "2": "b" }
2425

2526
// c) What does Object.entries return? Why is it needed in this program?
27+
/* Object.entries(obj) returns an array of [key, value] pairs. Example: Object.entries({ a:1, b:2 }) returns [["a", 1], ["b", 2]].
28+
It is needed because the loop "for (const [key, value] of Object.entries(obj))" let's each pair destructure easily.
29+
*/
2630

27-
// d) Explain why the current return value is different from the target output
31+
// d) Explain why the current return value is different from the target output - It is because this line "invertedObj.key = value;" uses literal string "key instead of the variable key" which is a wrong property name,
32+
// instead of this "invertedObj[value] = key;"
2833

2934
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
35+
function invert(obj) {
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;

‎Sprint-2/interpret/invert.test.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const invert = require("./invert.js");
2+
3+
test("inverts a single key-value pair", () => {
4+
expect(invert({ a: 1 })).toEqual({ 1: "a" });
5+
});
6+
7+
test("inverts multiple key-value pairs", () => {
8+
expect(invert({ a: 1, b: 2 })).toEqual({ 1: "a", 2: "b" });
9+
});
10+
11+
test("handles empty objects", () => {
12+
expect(invert({})).toEqual({});
13+
});
14+
15+
test("handles string values", () => {
16+
expect(invert({ x: "hello" })).toEqual({ hello: "x" });
17+
});

0 commit comments

Comments
 (0)