1.0.0 • Published 10 years ago
default-map v1.0.0
DefaultMap
This aims to provide a simple Map prototype with default value / value constructor.
Installation
npm install --save default-mapUsage
Requiring
var DefaultMap = require('default-map');Initialization
Constructor signature: DefaultMap(options).
With a default value
var map = new DefaultMap({ defaultValue: 'my default value' });With a default generator function
var map = new DefaultMap({ defaultGenerator: function (key) {
return 'the default value for the key: ' + key;
} });With initial data
var map = new DefaultMap({
data: { the: 'initial data' },
defaultValue: 'the default value'
});Checking key existence
map.has('key');Setting a value to a key
map.set('key', 'value');Getting the value of key
map.get('foo');If map has no key 'foo', it will be created using the default value / the default generator.
Deleting a key
map.delete('foo');Getting the entry set (useful for JSON serialization)
map.toHash();Checking if the map is empty
map.isEmpty();Iterating over the whole entry set
map.forEach(function (value, key, iteratedMap) {
console.log('Entry:', key, value);
}, this);Note that:
- Giving
thisas the second argument ofDefaultMap#forEachpreserves the calling context'sthis. - The third argument of the callback contains a reference to the iterated map.