|
1 | 1 | // Let's define how invert should work |
2 | 2 |
|
| 3 | + |
3 | 4 | // Given an object |
4 | 5 | // When invert is passed this object |
5 | 6 | // Then it should swap the keys and values in the object |
6 | 7 |
|
| 8 | + |
7 | 9 | // E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"} |
8 | 10 |
|
| 11 | + |
9 | 12 | function invert(obj) { |
10 | 13 | const invertedObj = {}; |
11 | 14 |
|
12 | 15 | for (const [key, value] of Object.entries(obj)) { |
13 | | - invertedObj.key = value; |
| 16 | + invertedObj[value] = key; |
14 | 17 | } |
15 | 18 |
|
16 | 19 | return invertedObj; |
17 | 20 | } |
18 | 21 |
|
| 22 | +module.exports = invert; |
| 23 | + |
| 24 | + |
19 | 25 | // a) What is the current return value when invert is called with { a : 1 } |
| 26 | +// Answer: { "1": "a" } |
| 27 | + |
20 | 28 |
|
21 | 29 | // b) What is the current return value when invert is called with { a: 1, b: 2 } |
| 30 | +// Answer: { "1": "a", "2": "b" } |
| 31 | + |
22 | 32 |
|
23 | 33 | // c) What is the target return value when invert is called with {a : 1, b: 2} |
| 34 | +// Answer: { "1": "a", "2": "b" } |
| 35 | + |
24 | 36 |
|
25 | 37 | // 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 | + |
26 | 41 |
|
27 | 42 | // 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 | + |
28 | 46 |
|
29 | 47 | // 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 | + |
0 commit comments