Skip to content

Commit 464f327

Browse files
answered questions and corrected function
1 parent 886ed6d commit 464f327

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

Sprint-2/interpret/invert.js

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,51 @@
66

77
// E.g. invert({x : 10, y : 20}), target output: {"10": "x", "20": "y"}
88

9-
function invert(obj) {
10-
const invertedObj = {};
9+
//function invert(obj) {
10+
// const invertedObj = {};
1111

12-
for (const [key, value] of Object.entries(obj)) {
13-
invertedObj.key = value;
14-
}
12+
// for (const [key, value] of Object.entries(obj)) {
13+
// invertedObj.key = value;
14+
// }
1515

16-
return invertedObj;
17-
}
16+
// return invertedObj;
17+
//}
1818

1919
// a) What is the current return value when invert is called with { a : 1 }
20+
// { key: 1 }
2021

2122
// b) What is the current return value when invert is called with { a: 1, b: 2 }
23+
// { key: 2 }
2224

2325
// c) What is the target return value when invert is called with {a : 1, b: 2}
26+
// {"1": "a", "2": "b" }
2427

2528
// c) What does Object.entries return? Why is it needed in this program?
29+
/* Object.entries returns an array of the object in pairs [key, value]. It is needed in this program
30+
to iterate through the object and access both the key and value at the same time, which is necessary
31+
for swapping them in the inverted object. */
2632

2733
// d) Explain why the current return value is different from the target output
2834

35+
/*The current return value is different from the target output because the implementation of the invert
36+
function is incorrect. Instead of using the variable key to set the property in the inverted object,
37+
it is using the literal string "key". This means that every time a key-value pair is processed,
38+
it overwrites the same property "key" in the inverted object, resulting in only the last key-value
39+
pair being stored. To fix this, we need to use bracket notation to set the property in the inverted object
40+
using the value as the key and the key as the value.*/
41+
2942
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
43+
44+
function invert(obj) {
45+
const invertedObj = {};
46+
47+
for (const [key, value] of Object.entries(obj)) {
48+
invertedObj[value] = key;
49+
}
50+
51+
return invertedObj;
52+
}
53+
54+
console.log(invert({ a: 1 })); // { "1": "a" }
55+
console.log(invert({ a: 1, b: 2 })); // { "1": "a", "2": "b" }
56+
console.log(invert({ x: 10, y: 20 })); // { "10": "x", "20": "y" }

0 commit comments

Comments
 (0)