Power of using Map in javascript

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.

要查看或添加评论,请登录

Palak Shah的更多文章

社区洞察

其他会员也浏览了