@@ -18,12 +18,61 @@ function invert(obj) {
1818
1919// a) What is the current return value when invert is called with { a : 1 }
2020
21+ { key : 1 }
22+
2123// b) What is the current return value when invert is called with { a: 1, b: 2 }
2224
25+ { key : 2 }
26+
2327// c) What is the target return value when invert is called with {a : 1, b: 2}
2428
29+ { 1 : "a" , 2 : "b" }
30+
2531// c) What does Object.entries return? Why is it needed in this program?
2632
33+ //Object.entries() returns an array of an object's key-value pairs, and it is needed in this program
34+ //so the for...of loop can access both each key and its corresponding value to swap them.
35+
2736// d) Explain why the current return value is different from the target output
2837
38+ //It is different because invertObj.key creates a property literally calley "key". If we want to use the value of
39+ //a variable as the property name, (invertedObj[value] = key) must be used instead.
40+
2941// e) Fix the implementation of invert (and write tests to prove it's fixed!)
42+
43+ function invert ( obj ) {
44+ const invertedObj = { } ;
45+
46+ for ( const [ key , value ] of Object . entries ( obj ) ) {
47+ invertedObj [ value ] = key ;
48+ }
49+
50+ return invertedObj ;
51+ }
52+
53+
54+
55+ describe ( "invert" , ( ) => {
56+ test ( "inverts an empty object" , ( ) => {
57+ expect ( invert ( { } ) ) . toEqual ( { } ) ;
58+ } ) ;
59+
60+ test ( "inverts a single property" , ( ) => {
61+ expect ( invert ( { a : 1 } ) ) . toEqual ( { 1 : "a" } ) ;
62+ } ) ;
63+
64+ test ( "inverts multiple properties" , ( ) => {
65+ expect ( invert ( { a : 1 , b : 2 } ) ) . toEqual ( {
66+ 1 : "a" ,
67+ 2 : "b" ,
68+ } ) ;
69+ } ) ;
70+
71+ test ( "works with other values" , ( ) => {
72+ expect ( invert ( { x : 10 , y : 20 } ) ) . toEqual ( {
73+ 10 : "x" ,
74+ 20 : "y" ,
75+ } ) ;
76+ } ) ;
77+ } ) ;
78+
0 commit comments