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.

const registry = {}
function set(name, meta) {
  registry[name] = meta
}
function get(name) {
  return registry[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 in Object.prototype break expectations and make interaction with this kind of hash-map data structures more cumbersome

  • When iterating using for..in we need to rely on Object#hasOwnProperty to make sure properties aren’t inherited

  • Iteration over list items with Object.keys(registry).forEach is 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.

const registry = {}
function set(name, meta) {
  registry['pkg:' + name] = meta
}
function get(name) {
  return registry['pkg:' + name]
}

An alternative could ...

Get Practical Modern JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.