1 | 'use strict';
|
2 | var hasher = require('../index');
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | exports = module.exports = HashTable;
|
17 |
|
18 | function HashTable(options){
|
19 | options = options || {};
|
20 | this.options = options;
|
21 | this._table = {};
|
22 | }
|
23 |
|
24 | HashTable.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 |
|
40 | HashTable.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 |
|
56 | HashTable.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 |
|
66 | HashTable.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 |
|
82 | HashTable.prototype.hasKey = function(key){
|
83 | return !!(this._table[key]);
|
84 | };
|
85 |
|
86 | HashTable.prototype.getValue = function(key){
|
87 | return this._table[key] ? this._table[key].value : undefined;
|
88 | };
|
89 |
|
90 | HashTable.prototype.getCount = function(key){
|
91 | return this._table[key] ? this._table[key].count : 0;
|
92 | };
|
93 |
|
94 | HashTable.prototype.table = function(){
|
95 | return this._table;
|
96 | };
|
97 |
|
98 | HashTable.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 |
|
111 | HashTable.prototype.reset = function(){
|
112 | this._table = {};
|
113 | return this;
|
114 | };
|