Skip to content

West Midlands | ITP-MAY25 | Saleh Yousef | Module-Data-Groups | Sprint-2 #622

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions Sprint-2/interpret/invert.js
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both tests pass - well done

Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,34 @@ function invert(obj) {
const invertedObj = {};

for (const [key, value] of Object.entries(obj)) {
invertedObj.key = value;
invertedObj[value] = key;
}

return invertedObj;
return invertedObj;
}

// a) What is the current return value when invert is called with { a : 1 }

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

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

{1 : a, 2 : b}
// c) What does Object.entries return? Why is it needed in this program?

// Object.entries returns an array of key-value pairs from the object. It is needed to iterate over both keys and values in the object.
// d) Explain why the current return value is different from the target output

// The current return value is incorrect because the code is assigning the value to the key instead of the key to the value in the inverted object.
// e) Fix the implementation of invert (and write tests to prove it's fixed!)

test("invert swaps keys and values in an object", () => {
const currentOutput = invert({ x: 10, y: 20 });
const targetOutput = { "10": "x", "20": "y" };

expect(currentOutput).toEqual(targetOutput);
});

test("invert handles multiple key-value pairs", () => {
const currentOutput = invert({ a: 1, b: 2, c: 3 });
const targetOutput = { "1": "a", "2": "b", "3": "c" };

expect(currentOutput).toEqual(targetOutput);
});