Power of using Map in javascript
Palak Shah
Passionate frontend developer skilled in React, TypeScript, Next.js, Redux, Zustand, Mobx, Nodejs, Tailwind CSS, and Webpack. Focused on web performance optimization and eager to explore opportunities in frontend and AI.
Map can use any type of data as the key than object:
Suppose you have different params and based on them to invoke different functions when some event happens in UI.
const actions = () => {
const functionA = () => {/* do something*/}
const functionB = () => {/* do something*/}
return new Map([
[{identity: 'guest', status:1}, functionA],
[{identity: 'guest', status:2}, functionA],
[{identity: 'guest', status:3}, functionA],
[{identity: 'guest', status:4}, functionA],
[{identity: 'guest', status:5}, functionB],
])
}
const onButtonClick = (identity, status) => {
let action = [...actions()].filter(([key,value]) => (key.identity == identity && key.status == status))
action?.forEach([key, value]) => value.call(this))
}
So, Map can contain objects as key which makes Map more usable in complex situations.
If the condition becomes more complex in above example, such as having 3 states for identity and 10 states for status, then you would end up defining 30 processing logics and often invoking same functions. There is much smarter way to define keys in Map:
领英推荐
const actions = () => {
const functionA = () => {/* do something*/}
const functionB = () => {/* do something*/}
return new Map([
[/^guest_[1-4]$/, functionA],
[/^guest_5$/, functionB]
])
}
const onButtonClick = (identity, status) => {
let action = [...actions()].filter(([key,value]) => (key.test(`${identity}_${status}`))
action?.forEach([key, value]) => value.call(this))
}
Here, the advantage of Map becomes even more prominent, as it allows using regex types as keys, which opens up endless possibilities.
And if the logic becomes more complex in future for sending a log event for each guest regardless of status, there can be a key like
[^guest_.*$/, functionC]
which will invoke functionC for every guest as identity.