Skip to content

Commit 3c56ceb

Browse files
committed
Invert Excercise
1 parent f110f2c commit 3c56ceb

File tree

2 files changed

+43
-8
lines changed

2 files changed

+43
-8
lines changed

Sprint-2/interpret/invert.js

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,42 @@
66

77
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
88

9-
function invert(obj) {
10-
const invertedObj = {};
9+
// function invert(obj) {
10+
// const invertedObj = {};
1111

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

16-
return invertedObj;
17-
}
16+
// return invertedObj;
17+
// }
1818

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

2122
// b) What is the current return value when invert is called with { a: 1, b: 2 }
23+
///2
2224

2325
// c) What is the target return value when invert is called with {a : 1, b: 2}
26+
//"1": "a", "2": "b"
2427

2528
// c) What does Object.entries return? Why is it needed in this program?
29+
//Object.entries({ a: 1, b: 2 }) // Returns: [["a", 1], ["b", 2]]
30+
// It converts an object to an array of [key, value] pairs so you can loop through them.
2631

2732
// d) Explain why the current return value is different from the target output
28-
33+
// The bug is invertedObj.key = value — this literally creates a property named "key"
34+
// instead of using the variable key. Also, it should swap: value becomes key, key becomes value.
2935
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
36+
37+
function invert(obj) {
38+
const invertedObj = {};
39+
40+
for (const [key, value] of Object.entries(obj)) {
41+
invertedObj[value] = key; // Use [value] as key, key as value
42+
}
43+
44+
return invertedObj;
45+
}
46+
47+
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 simple object", () => {
4+
expect(invert({ a: 1 })).toEqual({ 1: "a" });
5+
});
6+
7+
test("inverts multiple keys", () => {
8+
expect(invert({ a: 1, b: 2 })).toEqual({ 1: "a", 2: "b" });
9+
});
10+
11+
test("inverts x,y coordinates", () => {
12+
expect(invert({ x: 10, y: 20 })).toEqual({ 10: "x", 20: "y" });
13+
});
14+
15+
test("empty object returns empty", () => {
16+
expect(invert({})).toEqual({});
17+
});

0 commit comments

Comments
 (0)