|
9 | 9 | function invert(obj) { |
10 | 10 | const invertedObj = {}; |
11 | 11 |
|
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"); |
| 12 | + for (const [key, value] of Object.entries(obj)) { |
| 13 | + invertedObj.key = value; |
18 | 14 | } |
19 | 15 |
|
20 | 16 | return invertedObj; |
21 | 17 | } |
22 | 18 |
|
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 | | - |
44 | 19 | // a) What is the current return value when invert is called with { a : 1 } |
45 | | -//it returns a string describing the object. |
46 | 20 |
|
47 | 21 | // 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. |
49 | 22 |
|
50 | 23 | // 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"}. |
52 | 24 |
|
53 | 25 | // 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 |
56 | 26 |
|
57 | 27 | // 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. |
60 | 28 |
|
61 | 29 | // 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