Skip to content

Commit 352aef9

Browse files
Alex JamshidiAlex Jamshidi
authored andcommitted
completed invert.js
1 parent 3b91514 commit 352aef9

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

Sprint-2/interpret/invert.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,36 @@
66

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

9+
invert({ a: 1, b: 2 })
10+
911
function invert(obj) {
1012
const invertedObj = {};
1113

1214
for (const [key, value] of Object.entries(obj)) {
13-
invertedObj.key = value;
15+
invertedObj[value] = key
1416
}
15-
17+
console.log(invertedObj)
1618
return invertedObj;
1719
}
1820

21+
1922
// a) What is the current return value when invert is called with { a : 1 }
23+
// { key: 1 }
2024

2125
// b) What is the current return value when invert is called with { a: 1, b: 2 }
26+
// { key: 2 }
2227

2328
// c) What is the target return value when invert is called with {a : 1, b: 2}
29+
// {"1": "a", "2": "b"}
2430

2531
// c) What does Object.entries return? Why is it needed in this program?
32+
// It turns the object into an array of arrays
33+
// It's needed so the for..of loop can access the key:value pairs
2634

2735
// d) Explain why the current return value is different from the target output
36+
// invertedObj.key = value;
37+
// this line of code sets the key to "key"
38+
// even if that worked as intended, the key and value haven't been swapped
2839

2940
// e) Fix the implementation of invert (and write tests to prove it's fixed!)
41+
module.exports = invert;

Sprint-2/interpret/invert.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const invert = require("./invert.js");
2+
3+
describe("invert", () => {
4+
it("object returns inverted object", () => {
5+
6+
// a) What is the current return value when invert is called with { a : 1 }
7+
let object = { a : 1 };
8+
expect(invert(object)).toEqual({1: "a"})
9+
10+
// b) What is the current return value when invert is called with { a: 1, b: 2 }
11+
object = { a: 1, b: 2 };
12+
expect(invert(object)).toEqual({1: "a", 2: "b"})
13+
});
14+
});

0 commit comments

Comments
 (0)