Lightweight and context-free key-value maps
> map3 42 = 'dragons' // here be dragons!> map'3,42': 'dragons'> 3 42 in maptrue
> map object: 'with' stuff = 'big rip'> map'[object Object]': 'big rip'
To address this issue, ES6 introduced the
Map object, which removes the limit on what types of keys can be used.
But using the
Map constructor doesn't just break backwards compatibility - it also suffers from the fact that
Map instances can't be serialized to JSON.
Feel free to move on ahead if neither of these drawbacks apply to you, but I wanted to try my hand at creating a fast and serializable model for associative arrays based strictly on primitives instead of constructors. This module is what I came up with. 🎉
In this module, a map is any object with the fields
values, both of which are arrays.
var map =keys: 'foo' 3 42values: 'bar' 'dragons'
These two arrays are correlated ("associated") by index; e.g.
map.keys corresponds to
> mapkeys0 + ' -> ' + mapvalues0'foo -> bar'
The number of entries in a map (i.e. its size) can be determined via
map.keys.length, which is especially useful when iterating over each entry.
for var i = 0; i < mapkeyslength; i++var key = mapkeysivar value = mapvaluesiconsole
get(map, key) to retrieve a
key's corresponding value if it exists, otherwise
> var get =>3
To add new entries or alter existing ones, use
set(map, key, value).
> var set =>
has(map, key) to determine if
map contains an entry called
> var has =>true
To remove an entry, use
In this scenario,
clear returns the same value that
has(map, key) would have returned. Therefore, it will return
false if the given key is not found.
If you would like to clear all of a map's entries without creating any new objects, simply omit the second argument.
semibran/list- simple array operations