Maps Are Pretty Cool

(not this kind)

What's a Map?

  • Holds key / value pairs
  • Remembers key insertion order
  • Allows ANY value to be used as a key
const map = new Map()

map.set('a', 1);

map.get('a') // => 1

POJOs are kind of like maps

const editor = {
   name: "Emacs",
   isBetterThanVSCode: true,
   userShouldSwitchImmediately: true
}

But maps have some advantages...

  • No accidental keys (prototype)
  • User provided keys are safe (object injection attacks)
  • Keys can be of ANY value
  • Has a size property
  • Has built-in optimizations for frequent add/remove operations

Fun examples with DOM

import { ref } from 'vue';

let rowStates = {}
let activeRow;

document.querySelectorAll('tr').forEach((row) => {
  rowStates[row.id] = ref(false);

  row.addEventListener('click', () => {
    if (activeRow) rowStates[activeRow].value = false;

    activeRow = row;

    rowStates[row.id].value = true;
  });
});

Using a Map with less worry

import { ref, watchEffect } from 'vue';


let rowStates = new Map();
let activeRow;

document.querySelectorAll('tr').forEach((row) => {
   rowStates.set(row, ref(false));

    row.addEventListener('click', () => {
       if (activeRow) rowStates.get(activeRow).value = false;

        activeRow = row;


       rowStates.get(activeRow).value = true;
    });
});

Performance Check

Object Map
1,000 items 0.023ms 0.019ms (17%)
10,000 items 3.45ms 2.1ms(39%)
100,000 items 89.9ms 48.7ms(48%)

WeakMap cool bonus

WeakMap only retains key/pair values that are still in memory and haven't been garbage collected!

const map = new WeakMap()

const elem = document.getElementById('element')

map.set(elem, 'I do exist');
map.get(elem) // => 'I do exist'

/*
   some time later, elem.remove() is called and the elem is garbage collected
*/

map.get(elem) // => null

Fin

  • Maps are pretty cool
  • If you're using Objects to manage large k/v collections, maybe try a Map
  • If you're adding/deleting keys a lot, maybe try a Map
  • If you're removing non-string keys from a map often, try a WeakMap for free memory help

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Maps Are Pretty Cool

By hacknightly

Maps Are Pretty Cool

  • 10