|
1 | | -// |
2 | | -// b) What is the current return value when invert is called with { a: 1, b: 2 } |
| 1 | +// Let's define how invert should work |
3 | 2 |
|
4 | | -// c) What is the target return value when invert is called with {a : 1, b: 2} |
| 3 | +// Given an object |
| 4 | +// When invert is passed this object |
| 5 | +// Then it should swap the keys and values in the object |
5 | 6 |
|
6 | | -// c) What does Object.entries return? Why is it needed in this program? |
| 7 | +// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"} |
7 | 8 |
|
8 | | -// d) Explain why the current return value is different from the target output |
| 9 | +function invert(obj) { |
| 10 | + const invertedObj = {}; |
9 | 11 |
|
10 | | -// e) Fix the implementation of invert (and write tests to prove it's fixed!) |
| 12 | + for (const [key, value] of Object.entries(obj)) { |
| 13 | + invertedObj[value] = key; |
| 14 | + } |
| 15 | + |
| 16 | + return invertedObj; |
| 17 | +} |
| 18 | + |
| 19 | +console.log("invert.js loaded"); |
| 20 | + |
| 21 | +module.exports = invert; |
| 22 | + |
| 23 | +// a) What is the current return value when invert is called with {a : 1}? |
| 24 | +// The current return value when invert is called with {a: 1} is {key: 1}. |
| 25 | + |
| 26 | +// b) What is the current return value when invert is called with {a: 1, b: 2}? |
| 27 | +// The current return value when invert is called with {a: 1, b: 2} is {key: 2}. |
| 28 | + |
| 29 | +// c) What is the target return value when invert is called with {a: 1, b: 2}? |
| 30 | +// The target return value when invert is called with {a: 1, b: 2} is {1: a, 2: b}. |
| 31 | + |
| 32 | +// d) What does Object.entries return? Why is it needed in this program? |
| 33 | +// Object.entries() returns an array containing the key-value pairs of an object. |
| 34 | +// It is needed in this program because the function must access both the keys and the values in order to swap them. |
| 35 | + |
| 36 | +// e) Explain why the current return value is different from the target output. |
| 37 | +// The current return value is different from the target output because invertedObj.key = value does not use the variable key as the property name. |
| 38 | +// Bracket notation is needed to swap the keys and values. |
| 39 | + |
| 40 | +// f) Fix the implementation of invert (and write tests to prove it's fixed!) |
0 commit comments