Do you think this is a good usage of map in terms on readability / performance?
Lets say I'm making a list of notes but only allow 1 per day, You have a list of your notes:
[
{id: 1, date: "2021-10-12", content: "hello world!"},
{id: 2, date: "2021-10-13", content: "hope you have a great day!"}
]
We have a text field and a submit button, on click we call upsertNote()
which will update the array if it's the same day or will add a new record i.e:
usertNote({date: "2021-10-13", content: "how you get through today!"})
// output:
{id: 2, date: "2021-10-13", content: "how you get through today!"}
usertNote({date: "2021-10-14", content: "Future me!"})
// output:
{id: 3, date: "2021-10-14", content: "future me!"}
Notice how one updates the existing entry and the other creates a new one.
Now lets say we want to add to our existing list. We could do a search on the array for the id but what if we used a Map instead?
Is that better in terms on readability and performace?
e.g.
const toDoList = new Map(originalArray.map((i) => [i.id, i]))
const upsertToDoEntry = usertNote({date: "2021-10-14", content: "Future me!"})
toDoList.set(upsertToDoEntry.id, upsertToDoEntry)
// In our react if we wanted to map these out we'd have to do something like this:
Array.from(toDoList , ([id, toDoEntry]) => (
<span key={id}>{toDoEntry.content}</span>
)
Would you implement it this way? :)
Top comments (1)
Interesting approach, thanks. I probably would have just updated the existing object rather than creating a new array but your way is better with React. Is there any good examples of a case where you would use a Map object?