1- // Let's define how invert should work
2-
3- // Given an object
4- // When invert is passed this object
5- // Then it should swap the keys and values in the object
6-
7- // E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
8-
91function invert ( obj ) {
102 const invertedObj = { } ;
113
124 for ( const [ key , value ] of Object . entries ( obj ) ) {
13- invertedObj . key = value ;
5+ invertedObj [ value ] = key ;
146 }
157
168 return invertedObj ;
179}
1810
19- // a) What is the current return value when invert is called with { a : 1 }
11+ // a) Before the fix, invert({ a: 1 }) returned:
12+ // { key: 1 }
2013
21- // b) What is the current return value when invert is called with { a: 1, b: 2 }
14+ // b) Before the fix, invert({ a: 1, b: 2 }) returned:
15+ // { key: 2 }
16+ // The second loop replaced the first value.
2217
23- // c) What is the target return value when invert is called with {a : 1, b: 2}
18+ // c) The target return value is:
19+ // { "1": "a", "2": "b" }
2420
25- // c) What does Object.entries return? Why is it needed in this program?
21+ // d) Object.entries returns an array of [key, value] pairs.
22+ // It allows the loop to access both parts of each property.
2623
27- // d) Explain why the current return value is different from the target output
24+ // e) The original code used dot notation, which created a property
25+ // literally named "key" instead of using the value dynamically.
2826
29- // e) Fix the implementation of invert (and write tests to prove it's fixed!)
27+ module . exports = invert ;
0 commit comments