66
77// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
88
9- function invert ( obj ) {
9+ /* function invert(obj) {
1010 const invertedObj = {};
1111
1212 for (const [key, value] of Object.entries(obj)) {
1313 invertedObj.key = value;
1414 }
1515
16+ return invertedObj;
17+ }*/
18+
19+ //fixed code:
20+ function invert ( obj ) {
21+ const invertedObj = { } ;
22+
23+ for ( const [ key , value ] of Object . entries ( obj ) ) {
24+ invertedObj [ value ] = key ; // use the value as key, key as value
25+ }
26+
1627 return invertedObj ;
1728}
1829
30+ module . exports = invert ;
31+
1932// a) What is the current return value when invert is called with { a : 1 }
33+ // { key: 1 }
2034
2135// b) What is the current return value when invert is called with { a: 1, b: 2 }
36+ // { key: 2 }
2237
2338// c) What is the target return value when invert is called with {a : 1, b: 2}
39+ //{ "1": "a", "2": "b" }
40+
2441
2542// c) What does Object.entries return? Why is it needed in this program?
43+ /*Object.entries(obj) returns an array of [key, value] pairs.
44+ Needed because we want to loop through keys and values at the same time.*/
2645
2746// d) Explain why the current return value is different from the target output
2847
48+ /*Because the code is wrong in one place:
49+
50+ invertedObj.key = value;
51+
52+
53+ This uses the word "key" as a property name instead of using the variable key.
54+
55+ So instead of creating:
56+
57+ { 1: "a" }
58+
59+
60+ it always creates:
61+
62+ { key: 1 }
63+
64+
65+ and for multiple items, it keeps overwriting the same "key" */
66+
67+
2968// e) Fix the implementation of invert (and write tests to prove it's fixed!)
69+ // I did write upt there.
0 commit comments