File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 55// Then it should swap the keys and values in the object
66
77// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
8-
8+ /*
99function invert(obj) {
1010 const invertedObj = {};
1111
@@ -15,15 +15,29 @@ function invert(obj) {
1515
1616 return invertedObj;
1717}
18-
18+ console.log(invert({a:1,b:2}))*/
1919// a) What is the current return value when invert is called with { a : 1 }
20-
20+ // {key:1}
2121// b) What is the current return value when invert is called with { a: 1, b: 2 }
22-
22+ //{key:2}
2323// c) What is the target return value when invert is called with {a : 1, b: 2}
24-
24+ // {1:"a",2:"b"}
2525// c) What does Object.entries return? Why is it needed in this program?
26-
26+ // It returns an array of [key,value] pairs as two elements array and was used to return the object into enumerable array
2727// d) Explain why the current return value is different from the target output
28-
28+ // the function contain a bug as the dot notation here was overwriting the object in the loop also the return is not swapping the input
2929// e) Fix the implementation of invert (and write tests to prove it's fixed!)
30+
31+ function invert ( obj ) {
32+
33+
34+ const invertedObj = { } ;
35+
36+ for ( const [ key , value ] of Object . entries ( obj ) ) {
37+ invertedObj [ value ] = key ;
38+ }
39+
40+ return invertedObj ;
41+ }
42+
43+ module . exports = invert
Original file line number Diff line number Diff line change 1+ const invert = require ( "./invert.js" )
2+
3+ test ( 'given an empty object , returns an empty object' , ( ) => {
4+ expect ( invert ( { } ) ) . toEqual ( { } )
5+ } )
6+
7+ test ( 'Given an object with a single pair swaps ' , ( ) => {
8+ expect ( invert ( { a : "hello" } ) ) . toEqual ( { "hello" : "a" } )
9+ } )
10+
11+ test ( 'given an object with more than two pairs swaps the keys and values ' , ( ) => {
12+ expect ( invert ( { a : 1 , b : 2 } ) ) . toEqual ( { 1 : "a" , 2 : "b" } )
13+ } )
You can’t perform that action at this time.
0 commit comments