Skip to content

Commit f1c0798

Browse files
Complete Sprint 2 interpret exercise
1 parent fd0a7da commit f1c0798

2 files changed

Lines changed: 25 additions & 15 deletions

File tree

‎Sprint-2/interpret/invert.js‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,27 @@
1-
// Let's define how invert should work
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-
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
8-
91
function invert(obj) {
102
const invertedObj = {};
113

124
for (const [key, value] of Object.entries(obj)) {
13-
invertedObj.key = value;
5+
invertedObj[value] = key;
146
}
157

168
return invertedObj;
179
}
1810

19-
// a) What is the current return value when invert is called with { a : 1 }
11+
// a) Before the fix, invert({ a: 1 }) returned:
12+
// { key: 1 }
2013

21-
// b) What is the current return value when invert is called with { a: 1, b: 2 }
14+
// b) Before the fix, invert({ a: 1, b: 2 }) returned:
15+
// { key: 2 }
16+
// The second loop replaced the first value.
2217

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

25-
// c) What does Object.entries return? Why is it needed in this program?
21+
// d) Object.entries returns an array of [key, value] pairs.
22+
// It allows the loop to access both parts of each property.
2623

27-
// d) Explain why the current return value is different from the target output
24+
// e) The original code used dot notation, which created a property
25+
// literally named "key" instead of using the value dynamically.
2826

29-
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
27+
module.exports = invert;

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const invert = require("./invert.js");
2+
3+
test("swaps the keys and values in an object", () => {
4+
expect(invert({ a: 1, b: 2 })).toEqual({
5+
1: "a",
6+
2: "b",
7+
});
8+
});
9+
10+
test("returns an empty object for an empty object", () => {
11+
expect(invert({})).toEqual({});
12+
});

0 commit comments

Comments
 (0)