File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed
Expand file tree Collapse file tree 2 files changed +32
-1
lines changed 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}
1818
19+ module . exports = invert ;
20+
1921// a) What is the current return value when invert is called with { a : 1 }
22+ // { key: 1 }
2023
2124// b) What is the current return value when invert is called with { a: 1, b: 2 }
25+ // { key: 2 }
2226
2327// c) What is the target return value when invert is called with {a : 1, b: 2}
28+ // {"1": "a", "2": "b"}
2429
2530// c) What does Object.entries return? Why is it needed in this program?
31+ // Object.entries returns an array of the key value pairs in an object
32+ // It is needed because without it, iterating over the object is not possible
2633
2734// d) Explain why the current return value is different from the target output
35+ // InvertedObj.key creates a key called 'key' in the object
2836
2937// e) Fix the implementation of invert (and write tests to prove it's fixed!)
Original file line number Diff line number Diff line change 1+ const invert = require ( "./invert" ) ;
2+
3+ describe ( "invert" , ( ) => {
4+ test ( "object with numbers as values" , ( ) => {
5+ expect ( invert ( { a : 1 , b : 2 } ) ) . toEqual ( { 1 : "a" , 2 : "b" } ) ;
6+ } ) ;
7+
8+ test ( "1 pair in object" , ( ) => {
9+ expect ( invert ( { x : 99 } ) ) . toEqual ( { 99 : "x" } ) ;
10+ } ) ;
11+
12+ test ( "number keys with string values" , ( ) => {
13+ expect ( invert ( { 1 : "one" , 2 : "two" } ) ) . toEqual ( { one : "1" , two : "2" } ) ;
14+ } ) ;
15+
16+ test ( "empty object returns empty object" , ( ) => {
17+ expect ( invert ( { } ) ) . toEqual ( { } ) ;
18+ } ) ;
19+
20+ test ( "mixed types" , ( ) => {
21+ expect ( invert ( { a : 1 , b : "hello" } ) ) . toEqual ( { 1 : "a" , hello : "b" } ) ;
22+ } ) ;
23+ } ) ;
You can’t perform that action at this time.
0 commit comments