File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -10,20 +10,28 @@ function invert(obj) {
1010 const invertedObj = { } ;
1111
1212 for ( const [ key , value ] of Object . entries ( obj ) ) {
13- invertedObj . key = value ;
13+ invertedObj [ value ] = key ;
1414 }
1515
1616 return invertedObj ;
1717}
18+ module . exports = invert
1819
1920// a) What is the current return value when invert is called with { a : 1 }
21+ // {key: 1} because the invertedObj,ket = value does not use the variable key
22+
2023
2124// b) What is the current return value when invert is called with { a: 1, b: 2 }
25+ // {key:2} the loop runs twice and the second iteration replaces the first one so the answer becomes 2
2226
2327// c) What is the target return value when invert is called with {a : 1, b: 2}
28+ // The target return value is to swap the keys and values so {a:1, b:2} becomes {1:a, 2:b}
2429
2530// c) What does Object.entries return? Why is it needed in this program?
31+ // Object.entries() turns an object into an array containing key-value pairs
2632
2733// d) Explain why the current return value is different from the target output
28-
34+ // invertedObj.key means to create or access an object called key
35+ // and inverted invertedObj[key] means to use whatever value is stored in the key variable
2936// e) Fix the implementation of invert (and write tests to prove it's fixed!)
37+
Original file line number Diff line number Diff line change 1+ const invert = require ( "./invert.js" ) ;
2+
3+ test ( "inverts an object with one property" , ( ) => {
4+ expect ( invert ( { a : 1 } ) ) . toEqual ( {
5+ 1 : "a" ,
6+ } ) ;
7+ } ) ;
8+
9+ test ( "inverts an object with multiple properties" , ( ) => {
10+ expect ( invert ( { a : 1 , b : 2 } ) ) . toEqual ( {
11+ 1 : "a" ,
12+ 2 : "b" ,
13+ } ) ;
14+ } ) ;
15+
16+ test ( "inverts the example object" , ( ) => {
17+ expect ( invert ( { x : 10 , y : 20 } ) ) . toEqual ( {
18+ 10 : "x" ,
19+ 20 : "y" ,
20+ } ) ;
21+ } ) ;
You can’t perform that action at this time.
0 commit comments