UNPKG

2.63 kBJavaScriptView Raw
1'use strict';
2var hasher = require('../index');
3
4/**
5 * Setup a HashTable instance with options
6 * Options:
7 *
8 * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5'
9 * - `excludeValues` {true|*false} hash object keys, values ignored
10 * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64'
11 * * = default
12 *
13 * @param options
14 * @api public
15 */
16exports = module.exports = HashTable;
17
18function HashTable(options){
19 options = options || {};
20 this.options = options;
21 this._table = {};
22}
23
24HashTable.prototype.add = function(/* values to be added */){
25 var self = this;
26 var args = Array.prototype.slice.call(arguments, 0);
27 args.forEach(function(obj){
28 if(Object.prototype.toString.call(obj) === '[object Array]'){
29 obj.forEach(function(val){
30 self._addObject(val);
31 });
32 }else{
33 self._addObject(obj);
34 }
35 });
36
37 return this;
38};
39
40HashTable.prototype.remove = function(/* values to be removed */){
41 var self = this;
42 var args = Array.prototype.slice.call(arguments, 0);
43 args.forEach(function(obj){
44 if(Object.prototype.toString.call(obj) === '[object Array]'){
45 obj.forEach(function(val){
46 self._removeObject(val);
47 });
48 }else{
49 self._removeObject(obj);
50 }
51 });
52
53 return this;
54};
55
56HashTable.prototype._removeObject = function(object){
57 var hash = hasher(object, this.options),
58 count = this.getCount(hash);
59 if(count<=1) {
60 delete this._table[hash];
61 } else {
62 this._table[hash].count = count-1;
63 }
64};
65
66HashTable.prototype._addObject = function(object){
67 var hash = hasher(object, this.options);
68
69 if(this._table[hash]){
70 this._table[hash].count++;
71 if(this.options.excludeValues){
72 this._table[hash].value.push(object);
73 }
74 }else{
75 this._table[hash] = {
76 value: this.options.excludeValues ? [object] : object,
77 count: 1
78 };
79 }
80};
81
82HashTable.prototype.hasKey = function(key){
83 return !!(this._table[key]);
84};
85
86HashTable.prototype.getValue = function(key){
87 return this._table[key] ? this._table[key].value : undefined;
88};
89
90HashTable.prototype.getCount = function(key){
91 return this._table[key] ? this._table[key].count : 0;
92};
93
94HashTable.prototype.table = function(){
95 return this._table;
96};
97
98HashTable.prototype.toArray = function(){
99 var keys = Object.keys(this._table);
100 var arr = [];
101 for(var i = 0;i < keys.length;i++){
102 arr.push({
103 value: this._table[keys[i]].value,
104 count: this._table[keys[i]].count,
105 hash: keys[i]
106 });
107 }
108 return arr;
109};
110
111HashTable.prototype.reset = function(){
112 this._table = {};
113 return this;
114};