A pretty great use-case for Map in JS

A pretty great use-case for Map in JS

Map can store anything as a key. That means things like functions, objects, etc. can be keys, unlike objects where only numbers or strings can be keys, and if you try to force a non alphanumeric type as a key in a POJO, their .toString() representation is used for the key instead.


POJO

x = {}
x[new Date()] = 'lol'
Object.keys(x)
> ["Fri Dec 06 2019 12:04:58 GMT+0530 (India Standard Time)"]


Map

y = new Map()
y.set(new Date(), 'lol')
y.keys().next().value
> Fri Dec 06 2019 12:04:48 GMT+0530 (India Standard Time) // Date object, just printed as a string (but not within quotes, because a representation is being printed, not an actual string
y.keys().next().value.toISOString()
> "2019-12-06T06:34:48.792Z"

What was my use-case?

I’m working on a calendar component, and because of how I’m structuring the state, I would like the calendar data grouped by date, or, Moment (since that’s what we’re using). My alternatives were to either group by a string representation of the dates, or try and store the Moment itself so I continue to have access to all the methods on a moment object when I’m reading the keys. Map was perfect for this.

The down-sides?
Map is not serializable. That is not to say that you can’t write custom logic to serialize or deserialize a Map, but that’s the problem. You have to write custom code to do it. JS doesn’t do it for you. Also, if you store it in the state anyway, you will get something serialized, but it’ll not be the exact representation, it’ll be the best it can do to turn it into a string.

x = new Map()
x.set(1, 'lol')
JSON.stringify(x)
> "{}" // of course it didn't work

This means that if you store a Map in Redux, you have a non serializable entity in your store, and this is advised against as now you’re either prone to mutations that aren’t really caused by you, or are unavoidable due to the nature of Maps or Classes in general.


Note: Serialization and Deserialization

This just means that your state should be “exportable” and “importable” as a JSON object. Hence, you should be able to obtain your state in a JSON file, for example. So things like functions, classes, and anything that can only work on references or such JS specific constructs aren’t supported. If you don’t care about serialization, then the downsides don’t apply. Here’s a link from the Redux FAQ about this: https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state



Leave a Reply

Your email address will not be published. Required fields are marked *