File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66
77// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
88
9+ invert ( { a : 1 , b : 2 } )
10+
911function invert ( obj ) {
1012 const invertedObj = { } ;
1113
1214 for ( const [ key , value ] of Object . entries ( obj ) ) {
13- invertedObj . key = value ;
15+ invertedObj [ value ] = key
1416 }
15-
17+ console . log ( invertedObj )
1618 return invertedObj ;
1719}
1820
21+
1922// a) What is the current return value when invert is called with { a : 1 }
23+ // { key: 1 }
2024
2125// b) What is the current return value when invert is called with { a: 1, b: 2 }
26+ // { key: 2 }
2227
2328// c) What is the target return value when invert is called with {a : 1, b: 2}
29+ // {"1": "a", "2": "b"}
2430
2531// c) What does Object.entries return? Why is it needed in this program?
32+ // It turns the object into an array of arrays
33+ // It's needed so the for..of loop can access the key:value pairs
2634
2735// d) Explain why the current return value is different from the target output
36+ // invertedObj.key = value;
37+ // this line of code sets the key to "key"
38+ // even if that worked as intended, the key and value haven't been swapped
2839
2940// e) Fix the implementation of invert (and write tests to prove it's fixed!)
41+ module . exports = invert ;
Original file line number Diff line number Diff line change 1+ const invert = require ( "./invert.js" ) ;
2+
3+ describe ( "invert" , ( ) => {
4+ it ( "object returns inverted object" , ( ) => {
5+
6+ // a) What is the current return value when invert is called with { a : 1 }
7+ let object = { a : 1 } ;
8+ expect ( invert ( object ) ) . toEqual ( { 1 : "a" } )
9+
10+ // b) What is the current return value when invert is called with { a: 1, b: 2 }
11+ object = { a : 1 , b : 2 } ;
12+ expect ( invert ( object ) ) . toEqual ( { 1 : "a" , 2 : "b" } )
13+ } ) ;
14+ } ) ;
You can’t perform that action at this time.
0 commit comments