From 5dc0202d5677de6132ad2fade9be26d3c97d543e Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 5 Jan 2017 03:59:35 -0800 Subject: [PATCH] utils: add map. --- lib/utils/map.js | 124 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 lib/utils/map.js diff --git a/lib/utils/map.js b/lib/utils/map.js new file mode 100644 index 00000000..fb491989 --- /dev/null +++ b/lib/utils/map.js @@ -0,0 +1,124 @@ +/*! + * map.js - hash table for bcoin + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). + * https://github.com/bcoin-org/bcoin + */ + +'use strict'; + +var assert = require('assert'); + +/** + * Map + * @constructor + */ + +function Map() { + if (!(this instanceof Map)) + return new Map(); + + this.map = {}; + this.size = 0; +} + +/** + * Get map keys. + * @returns {String[]} + */ + +Map.prototype.keys = function keys() { + return Object.keys(this.map); +}; + +/** + * Get map values. + * @returns {Object[]} + */ + +Map.prototype.values = function values() { + var keys = Object.keys(this.map); + var values = []; + var i, key; + + for (i = 0; i < keys.length; i++) { + key = keys[i]; + values.push(this.map[key]); + } + + return values; +}; + +/** + * Get item from map. + * @param {String} key + * @returns {Object|null} + */ + +Map.prototype.get = function get(key) { + return this.map[key]; +}; + +/** + * Test whether map has an item. + * @param {String} key + * @returns {Boolean} + */ + +Map.prototype.has = function has(key) { + return this.map[key] !== undefined; +}; + +/** + * Set a key to value in map. + * @param {String} key + * @param {Object} value + * @returns {Boolean} + */ + +Map.prototype.set = function set(key, value) { + var item = this.map[key]; + + assert(value !== undefined); + + this.map[key] = value; + + if (item === undefined) { + this.size++; + return true; + } + + return false; +}; + +/** + * Remove an item from map. + * @param {String} key + * @returns {Object|null} + */ + +Map.prototype.remove = function remove(key) { + var item = this.map[key]; + + if (item === undefined) + return; + + delete this.map[key]; + this.size--; + + return item; +}; + +/** + * Reset the map. + */ + +Map.prototype.reset = function reset() { + this.map = {}; + this.size = 0; +}; + +/* + * Expose + */ + +module.exports = Map;