66
77// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
88
9- function invert ( obj ) {
10- const invertedObj = { } ;
9+ // function invert(obj) {
10+ // const invertedObj = {};
1111
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+ // }
1515
16- return invertedObj ;
17- }
16+ // return invertedObj;
17+ // }
1818
1919// a) What is the current return value when invert is called with { a : 1 }
20+ // 1
2021
2122// b) What is the current return value when invert is called with { a: 1, b: 2 }
23+ ///2
2224
2325// c) What is the target return value when invert is called with {a : 1, b: 2}
26+ //"1": "a", "2": "b"
2427
2528// c) What does Object.entries return? Why is it needed in this program?
29+ //Object.entries({ a: 1, b: 2 }) // Returns: [["a", 1], ["b", 2]]
30+ // It converts an object to an array of [key, value] pairs so you can loop through them.
2631
2732// d) Explain why the current return value is different from the target output
28-
33+ // The bug is invertedObj.key = value — this literally creates a property named "key"
34+ // instead of using the variable key. Also, it should swap: value becomes key, key becomes value.
2935// e) Fix the implementation of invert (and write tests to prove it's fixed!)
36+
37+ function invert ( obj ) {
38+ const invertedObj = { } ;
39+
40+ for ( const [ key , value ] of Object . entries ( obj ) ) {
41+ invertedObj [ value ] = key ; // Use [value] as key, key as value
42+ }
43+
44+ return invertedObj ;
45+ }
46+
47+ module . exports = invert ;
0 commit comments