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)) {
@@ -15,15 +15,42 @@ function invert(obj) {
1515
1616 return invertedObj;
1717}
18+ */
1819
1920// a) What is the current return value when invert is called with { a : 1 }
21+ // the current return value is { key: 1 }
2022
2123// b) What is the current return value when invert is called with { a: 1, b: 2 }
24+ // the current return value is { key: 1, key: 2 }
2225
2326// c) What is the target return value when invert is called with {a : 1, b: 2}
27+ // the target return value is { "1": "a", "2": "b" }
2428
2529// c) What does Object.entries return? Why is it needed in this program?
30+ /* Object.entries returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
31+ In this program, it is needed to iterate over the key-value pairs of the input object so that we can swap them and create the inverted object.
32+ */
2633
2734// d) Explain why the current return value is different from the target output
35+ /* The current return value is different from the target output because in the current implementation,
36+ we are assigning the value to a property named "key" in the inverted object,
37+ which means that every key-value pair in the input object will overwrite the same "key" property in the inverted object.
38+ As a result, only the last key-value pair from the input object will be reflected in the inverted object, leading to incorrect output.
39+ To achieve the target output, we need to use the value from the input object as the key in the inverted object and
40+ the key from the input object as the value in the inverted object.
41+ */
2842
2943// e) Fix the implementation of invert (and write tests to prove it's fixed!)
44+ function invert ( obj ) {
45+ const invertedObj = { } ;
46+
47+ for ( const [ key , value ] of Object . entries ( obj ) ) {
48+ invertedObj [ value ] = key ;
49+ }
50+
51+ return invertedObj ;
52+ }
53+
54+
55+
56+ expect ( invert ( { a : 1 , b : 2 } ) ) . toEqual ( { '1' : 'a' , '2' : 'b' } ) ;
0 commit comments