Skip to content
Cheng Lou edited this page Jun 27, 2013 · 3 revisions

Kind of a stopgap measure for the upcoming JavaScript Map

Note: due to JavaScript's limitations, hashing something other than Boolean, Number, String, Undefined, Null, RegExp, Function requires a hack that inserts a hidden unique property into the object. This means set, get, has and delete must employ the same object, and not a mere identical copy as in the case of, say, a string.

Overview example:

var map = new Map({'alice': 'wonderland', 20: 'ok'});
map.set('20', 5); // => 5
map.get('20'); // => 5
map.has('alice'); // => true
map.delete(20) // => true
var arr = [1, 2];
map.add(arr, 'goody'); // => 'goody'
map.has(arr); // => true
map.has([1, 2]); // => false. Needs to compare by reference
map.forEach(function(key, value) {
  console.log(key, value);
});

Properties:

  • size: The total number of (key, value) pairs.

Instance Methods

Pass an optional object whose (key, value) pair will be hashed. Careful not to pass something like {5: 'hi', '5': 'hello'}, since JavaScript's native object behavior will crush the first 5 property before it gets to constructor.

The hash function for hashing keys is public. Feel free to replace it with your own. The makeHash parameter is optional and accepts a boolean (defaults to false) indicating whether or not to produce a new hash (for the first use, naturally).

Returns: the hash.

Returns: value.

Returns: value corresponding to the key, or undefined if not found.

Check whether a value exists for the key.

Returns: true or false.

Remove the (key, value) pair.

Returns: true or false. Unlike most of this library, this method doesn't return the deleted value. This is so that it conforms to the future JavaScript map.delete()'s behavior.

Traverse through the map. Pass a function of the form fn(key, value).

Returns: undefined.

Clone this wiki locally