|
9 | 9 | function invert(obj) { |
10 | 10 | const invertedObj = {}; |
11 | 11 |
|
12 | | - for (const [key, value] of Object.entries(obj)) { |
13 | | - invertedObj.key = value; |
| 12 | + if (Object.prototype.toString.call(obj) === "[object Object]") { |
| 13 | + for (const [key, value] of Object.entries(obj)) { |
| 14 | + invertedObj[value] = key; |
| 15 | + } |
| 16 | + } else { |
| 17 | + throw new Error("error invalid input entered, expecting an object"); |
14 | 18 | } |
15 | 19 |
|
16 | 20 | return invertedObj; |
17 | 21 | } |
18 | 22 |
|
| 23 | +module.exports = invert; |
| 24 | + |
| 25 | +console.log( |
| 26 | + `the return value when invert is called with ${invert({ |
| 27 | + cars: { toyota: 2, bmw: 1, benz: 4 }, |
| 28 | + })}` |
| 29 | +); |
| 30 | + |
| 31 | +/* |
| 32 | +for (const property in obj) { |
| 33 | + if (typeof obj[property] !== "string") { |
| 34 | + throw new Error( |
| 35 | + "error invalid input entered, expecting an object to have only strings as values" |
| 36 | + ); |
| 37 | + } else { |
| 38 | + |
| 39 | + } |
| 40 | + } |
| 41 | +
|
| 42 | +*/ |
| 43 | + |
19 | 44 | // a) What is the current return value when invert is called with { a : 1 } |
| 45 | +//it returns a string describing the object. |
20 | 46 |
|
21 | 47 | // b) What is the current return value when invert is called with { a: 1, b: 2 } |
| 48 | +//it aso returns a string describing the object. |
22 | 49 |
|
23 | 50 | // c) What is the target return value when invert is called with {a : 1, b: 2} |
| 51 | +//the target return value is {"1": "a", "2": "b"}. |
24 | 52 |
|
25 | 53 | // c) What does Object.entries return? Why is it needed in this program? |
| 54 | +//it returns an array made up of arrays of the original objects key - value pairs. |
| 55 | +//it allows us to unpack the contents of the object into an array which can then be used to create the new object |
26 | 56 |
|
27 | 57 | // d) Explain why the current return value is different from the target output |
| 58 | +//because we used dot notation to assign a value to our key, this creates a property called key |
| 59 | +//and assigns it a value. we want our key to get its name from a variable so we need to use bracket notation. |
28 | 60 |
|
29 | 61 | // e) Fix the implementation of invert (and write tests to prove it's fixed!) |
| 62 | +//we can fix it by using invertedObj[value] = key. |
0 commit comments