File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11// Let's define how invert should work
2-
2+ // inverse typically means to reverse the key and value in an object.
33// Given an object
44// When invert is passed this object
55// Then it should swap the keys and values in the object
6-
76// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
8-
97function invert ( obj ) {
108 const invertedObj = { } ;
11-
129 for ( const [ key , value ] of Object . entries ( obj ) ) {
13- invertedObj . key = value ;
10+ invertedObj [ value ] = key ;
1411 }
15-
1612 return invertedObj ;
1713}
1814
19- // a) What is the current return value when invert is called with { a : 1 }
20-
21- // b) What is the current return value when invert is called with { a: 1, b: 2 }
22-
23- // c) What is the target return value when invert is called with {a : 1, b: 2}
24-
25- // c) What does Object.entries return? Why is it needed in this program?
26-
27- // d) Explain why the current return value is different from the target output
28-
29- // e) Fix the implementation of invert (and write tests to prove it's fixed!)
15+ module . exports = invert ;
Original file line number Diff line number Diff line change 1+ const invert = require ( "./invert" ) ;
2+
3+ test ( "invert swaps keys and values in an object" , ( ) => {
4+ const input = { a : 1 , b : 2 } ;
5+ const expectedOutput = { "1" : "a" , "2" : "b" } ;
6+ expect ( invert ( input ) ) . toEqual ( expectedOutput ) ;
7+ } ) ;
8+
9+ test ( "invert returns an empty object when given an empty object" , ( ) => {
10+ expect ( invert ( { } ) ) . toEqual ( { } ) ;
11+ } ) ;
12+
13+ test ( "invert works with string values" , ( ) => {
14+ const input = { x : "10" , y : "20" } ;
15+ const expectedOutput = { "10" : "x" , "20" : "y" } ;
16+ expect ( invert ( input ) ) . toEqual ( expectedOutput ) ;
17+ } ) ;
You can’t perform that action at this time.
0 commit comments