|
6 | 6 |
|
7 | 7 | // E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"} |
8 | 8 |
|
9 | | -function invert(obj) { |
10 | | - const invertedObj = {}; |
| 9 | +//function invert(obj) { |
| 10 | +// const invertedObj = {}; |
11 | 11 |
|
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 | +// } |
15 | 15 |
|
16 | | - return invertedObj; |
17 | | -} |
| 16 | +// return invertedObj; |
| 17 | +//} |
18 | 18 |
|
19 | 19 | // a) What is the current return value when invert is called with { a : 1 } |
| 20 | +// { key: 1 } |
20 | 21 |
|
21 | 22 | // b) What is the current return value when invert is called with { a: 1, b: 2 } |
| 23 | +// { key: 2 } |
22 | 24 |
|
23 | 25 | // c) What is the target return value when invert is called with {a : 1, b: 2} |
| 26 | +// {"1": "a", "2": "b" } |
24 | 27 |
|
25 | 28 | // c) What does Object.entries return? Why is it needed in this program? |
| 29 | +/* Object.entries returns an array of the object in pairs [key, value]. It is needed in this program |
| 30 | + to iterate through the object and access both the key and value at the same time, which is necessary |
| 31 | + for swapping them in the inverted object. */ |
26 | 32 |
|
27 | 33 | // d) Explain why the current return value is different from the target output |
28 | 34 |
|
| 35 | +/*The current return value is different from the target output because the implementation of the invert |
| 36 | +function is incorrect. Instead of using the variable key to set the property in the inverted object, |
| 37 | +it is using the literal string "key". This means that every time a key-value pair is processed, |
| 38 | +it overwrites the same property "key" in the inverted object, resulting in only the last key-value |
| 39 | +pair being stored. To fix this, we need to use bracket notation to set the property in the inverted object |
| 40 | +using the value as the key and the key as the value.*/ |
| 41 | + |
29 | 42 | // e) Fix the implementation of invert (and write tests to prove it's fixed!) |
| 43 | + |
| 44 | +function invert(obj) { |
| 45 | + const invertedObj = {}; |
| 46 | + |
| 47 | + for (const [key, value] of Object.entries(obj)) { |
| 48 | + invertedObj[value] = key; |
| 49 | + } |
| 50 | + |
| 51 | + return invertedObj; |
| 52 | +} |
| 53 | + |
| 54 | +console.log(invert({ a: 1 })); // { "1": "a" } |
| 55 | +console.log(invert({ a: 1, b: 2 })); // { "1": "a", "2": "b" } |
| 56 | +console.log(invert({ x: 10, y: 20 })); // { "10": "x", "20": "y" } |
0 commit comments