Skip to content

Commit a11bae4

Browse files
committed
interpret
1 parent 66308a3 commit a11bae4

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

Sprint-2/interpret/invert.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,49 @@
11
// Let's define how invert should work
22

3+
34
// Given an object
45
// When invert is passed this object
56
// Then it should swap the keys and values in the object
67

8+
79
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
810

11+
912
function invert(obj) {
1013
const invertedObj = {};
1114

1215
for (const [key, value] of Object.entries(obj)) {
13-
invertedObj.key = value;
16+
invertedObj[value] = key;
1417
}
1518

1619
return invertedObj;
1720
}
1821

22+
module.exports = invert;
23+
24+
1925
// a) What is the current return value when invert is called with { a : 1 }
26+
// Answer: { "1": "a" }
27+
2028

2129
// b) What is the current return value when invert is called with { a: 1, b: 2 }
30+
// Answer: { "1": "a", "2": "b" }
31+
2232

2333
// c) What is the target return value when invert is called with {a : 1, b: 2}
34+
// Answer: { "1": "a", "2": "b" }
35+
2436

2537
// c) What does Object.entries return? Why is it needed in this program?
38+
// Answer: Object.entries(obj) returns an array of [key, value] pairs,
39+
// It is needed so we can loop over the object and easily get both key and value in the for...of loop using array destructuring: [key, value].
40+
2641

2742
// d) Explain why the current return value is different from the target output
43+
// Answer: In this implementation, the current return value already matches the target output, because we correctly use the value as the new key
44+
// and the key as the new value: invertedObj[value] = key.
45+
2846

2947
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
48+
// Answer: No changes needed to the implementation; it already works as required.
49+

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+
// Given an object
4+
// When invert is passed this object
5+
// Then it should swap the keys and values in the object
6+
7+
test("inverts single key-value pair", () => {
8+
expect(invert({ a: 1 })).toEqual({ 1: "a" });
9+
});
10+
11+
test("inverts multiple key-value pairs", () => {
12+
expect(invert({ a: 1, b: 2 })).toEqual({ 1: "a", 2: "b" });
13+
});
14+
15+
test("inverts empty object to empty object", () => {
16+
expect(invert({})).toEqual({});
17+
});

0 commit comments

Comments
 (0)