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- function invert ( obj ) { // obj{} is the input of invert function
10- const invertedObj = { } ; // says that invertedObj is a empty object {}
11-
12- for ( const [ key , value ] of Object . entries ( obj ) ) { //'for' is looping the key and value of the object
13- invertedObj [ key ] = value ; // stored. Object.entires(obj) returns an array of array
14- } // key in a bracket [] lets you use a variable called key
9+ function invert ( obj ) {
10+ const invertedObj = { } ;
11+ for ( const [ key , value ] of Object . entries ( obj ) ) {
12+ invertedObj [ value ] = key ;
13+ }
1514
1615 return invertedObj ;
1716}
@@ -25,16 +24,13 @@ function invert(obj) { // obj{} is the input of invert funct
2524// c) What is the target return value when invert is called with {a : 1, b: 2}
2625// {"1": "a", "2":"b"}
2726
28-
2927// c) What does Object.entries return? Why is it needed in this program?
3028// It returns an array of property into the object
3129
3230// d) Explain why the current return value is different from the target output
33- // The current return value only shows {key: 2}. It doesn't show the first key and value only the second,
34- // and it doesn't specify the second key. Its just defined as 'key'.
31+ // The current return value only shows {key: 2}. It doesn't show the first key and value only the second,
32+ // and it doesn't specify the second key. Its just defined as 'key'.
3533
3634// e) Fix the implementation of invert (and write tests to prove it's fixed!)
3735
3836module . exports = invert ;
39-
40-
Original file line number Diff line number Diff line change 11const invert = require ( "./invert.js" ) ;
22
3- test ( "When invert is passed, keys and values in the object should be swapped " , ( ) => {
4- expect ( { x : 10 , y : 20 } ) . toEqual ( { x : 10 , y : 20 } ) ;
3+ test ( "when passed invert swaps single key-value pair" , ( ) => {
4+ expect ( invert ( { a : 1 } ) ) . toEqual ( { "1" : "a" } ) ;
55} ) ;
6+
7+ test ( "When invert is passed, multiple keys and values in the object should be swapped " , ( ) => {
8+ expect ( invert ( { x : 10 , y : 20 } ) ) . toEqual ( { "10" : "x" , "20" : "y" } )
9+ } ) ;
10+
11+ test ( "when passed invert swaps string values" , ( ) => {
12+ expect ( invert ( { first : "hello" , second : "world" } ) ) . toEqual ( { hello : "first" , world : "second" } ) ;
13+ } ) ;
You can’t perform that action at this time.
0 commit comments