Let's have a brief refresher on JavaScript data structures. I believe Maps and Sets are the most underrated data structures in JavaScript/TypeScript. In my opinion, they are massively useful in many cases and can reduce headaches. Let's go over the new Map() for this one: Based on the official MDN definition, which I bring here, the Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value. Map objects are collections of key-value pairs. A key in the Map may only occur once; it is unique in the Map's collection. A Map object is iterated by key-value pairs — a for...of loop returns a 2-member array of [key, value] for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the set() method (that is, there wasn't a key with the same value already in the map when set() was called). The specification requires maps to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N). Key equality: Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated 0 and -0 as different. Check browser compatibility.) This means NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. Also, for object keys, equality is based on object identity. They are compared by reference, not by value. See Using the Map object for examples. Objects vs. Maps: Object is similar to Map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. For this reason (and because there were no built-in alternatives), Object has been used as Map historically. One of the common use cases of a Map can be to build an LRU data structure or cache mechanism. We have the inserted items in an ordered list, and we can have a size limit and store/read data from the cache. Official Mozilla MDN: https://lnkd.in/dyyc_cPP). Hackr io for more info: https://lnkd.in/dR-hfD8r #javascript #datastructure #algorithm #map #typescript #frontend #backend #nodejs #javascriptengineer #frontendengineer
Use WeakMap for that to free some memory and add timestamp plus cache invalidation strategies. Then it will be ideal.
One of my favorite real‑world use cases for Map is removing duplicate objects from an array based on a single field and you can do it in just one line of code: function uniqueBy<T, K extends keyof T>(arr: T[], key: K): T[] { return [...newMap(arr.map(item => [item[key], item])).values()]; }