Chapter 5. Leveraging ECMAScript Collections
JavaScript data structures are flexible enough that we’re able to turn any object into a hash-map, where we map string keys to arbitrary values. For example, one might use an object to map npm package names to their metadata, as shown next.
constregistry={}functionset(name,meta){registry[name]=meta}functionget(name){returnregistry[name]}set('contra',{description:'Asynchronous flow control'})set('dragula',{description:'Drag and drop'})set('woofmark',{description:'Markdown and WYSIWYG editor'})
There are several problems with this approach, outlined here:
-
Security issues where user-provided keys like
__proto__,toString, or anything inObject.prototypebreak expectations and make interaction with this kind of hash-map data structures more cumbersome -
When iterating using
for..inwe need to rely onObject#hasOwnPropertyto make sure properties aren’t inherited -
Iteration over list items with
Object.keys(registry).forEachis also verbose -
Keys are limited to strings, making it hard to create hash-maps where you’d like to index values by DOM elements or other nonstring references
The first problem could be fixed using a prefix, and being careful to always get or set values in the hash-map through functions that add those prefixes, to avoid mistakes.
constregistry={}functionset(name,meta){registry['pkg:'+name]=meta}functionget(name){returnregistry['pkg:'+name]}
An alternative could ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access