DEV Community

John McElreavey
John McElreavey

Posted on

Good Map Usage?

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!"}
]
Enter fullscreen mode Exit fullscreen mode

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!"}
Enter fullscreen mode Exit fullscreen mode

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>
)
Enter fullscreen mode Exit fullscreen mode

Would you implement it this way? :)

Discussion (2)

Collapse
lukeshiru profile image
Luke Shiru

Nah, I would just use objects/arrays to avoid unwanted mutations:

const toDoList = [
    { id: 1, date: "2021-10-12", content: "hello world!" },
    { id: 2, date: "2021-10-13", content: "hope you have a great day!" }
];

// Reusable function to update or replace by an id property.
const addOrUpdateById = array => item => {
    const index = array.findIndex(({ id }) => id === item.id);

    return index >= 0
        ? [...array.slice(0, index), item, ...array.slice(index + 1)]
        : [...array, item];
};

// Because the util is curried, we create a new function from it...
const addOrUpdateToDo = addOrUpdateById(toDoList);

// We should use it to update the state in React
// but as an example, here we map trough it directly
addOrUpdateToDo(usertNote({ date: "2021-10-14", content: "Future me!" })).map(
    ({ id, content }) => <span key={id}>{content}</span>
);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
jmcelreavey profile image
John McElreavey Author

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?