London | 26-ITP-Jan | Angela McLeary | Sprint 2 | Sprint 2#1132
London | 26-ITP-Jan | Angela McLeary | Sprint 2 | Sprint 2#1132AngelaMcLeary wants to merge 16 commits intoCodeYourFuture:mainfrom
Conversation
| for (const [key, value] of Object.entries(obj)) { | ||
| invertedObj.key = value; | ||
| //create new keys and values to make them dynamic | ||
| let newKey = value.toString(); | ||
| let newValue = key.toString(); | ||
| invertedObj[newKey] = newValue; | ||
| } |
There was a problem hiding this comment.
What do you expect from the following function calls?
invert({ a: null })
invert({ a: undefined })
There was a problem hiding this comment.
Hi @cjyuan, Thanks for the feedback. I thought that it would return { null: 'a' } and { undefined: 'a' }.
However it returned nothing for both.
I see the problem clearly. When the function calls toString it is crashing. I've updated the code to use String(value) and String(key) instead, which safely converts all values (including null and undefined) without throwing an error. The function now works correctly for all the test cases.”
There was a problem hiding this comment.
Note:
- When a value (except symbol) is used as key, it is implicitly converted to its equivalent string value.
- Key is always a string (except when it is a symbol).
So you don't actually have to explicitly convert the old key or value to strings.
Just invertedObj[value] = key; will do.
…ut is a plain object, not an array correctly, and corrected contain.test.js
cjyuan
left a comment
There was a problem hiding this comment.
Changes look good. Well done.
| function tally() {} | ||
| function tally(list) { | ||
| //This object will store each item as a key and how many times it appears as a value. First declare an empty array | ||
| var counts = Object.create(null); |
There was a problem hiding this comment.
Should use let instead of var. var, when not used properly, can introduce unintended side effect.
Learners, PR Template
Self checklist
Changelist
This PR is about debugging, implementing and interpreting code.