Skip to content

Commit 7d8419a

Browse files
committed
add invert.js
1 parent ae3c218 commit 7d8419a

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

‎Sprint-2/interpret/invert.js‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,28 @@ 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
}
18+
module.exports = invert
1819

1920
// a) What is the current return value when invert is called with { a : 1 }
21+
// {key: 1} because the invertedObj,ket = value does not use the variable key
22+
2023

2124
// b) What is the current return value when invert is called with { a: 1, b: 2 }
25+
// {key:2} the loop runs twice and the second iteration replaces the first one so the answer becomes 2
2226

2327
// c) What is the target return value when invert is called with {a : 1, b: 2}
28+
// The target return value is to swap the keys and values so {a:1, b:2} becomes {1:a, 2:b}
2429

2530
// c) What does Object.entries return? Why is it needed in this program?
31+
// Object.entries() turns an object into an array containing key-value pairs
2632

2733
// d) Explain why the current return value is different from the target output
28-
34+
// invertedObj.key means to create or access an object called key
35+
// and inverted invertedObj[key] means to use whatever value is stored in the key variable
2936
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
37+

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const invert = require("./invert.js");
2+
3+
test("inverts an object with one property", () => {
4+
expect(invert({ a: 1 })).toEqual({
5+
1: "a",
6+
});
7+
});
8+
9+
test("inverts an object with multiple properties", () => {
10+
expect(invert({ a: 1, b: 2 })).toEqual({
11+
1: "a",
12+
2: "b",
13+
});
14+
});
15+
16+
test("inverts the example object", () => {
17+
expect(invert({ x: 10, y: 20 })).toEqual({
18+
10: "x",
19+
20: "y",
20+
});
21+
});

0 commit comments

Comments
 (0)