-
Notifications
You must be signed in to change notification settings - Fork 1
/
hashmap.js
105 lines (83 loc) · 1.95 KB
/
hashmap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* HashMap
* @author Ariel Flesler <[email protected]>
* @version 0.9.1
* Date: 9/28/2012
* Homepage: https://github.com/flesler/hashmap
*/
;(function(exports){
function HashMap() {
this.clear();
};
HashMap.prototype = {
constructor:HashMap,
// TODO: Implement a way to iterate (.each()?)
get:function(key) {
return this._data[this.hash(key)];
},
set:function(key, value) {
this._data[this.hash(key)] = value;
},
has:function(key) {
return this.hash(key) in this._data;
},
remove:function(key) {
delete this._data[this.hash(key)];
},
type:function(key) {
var str = Object.prototype.toString.call(key);
var type = str.slice(8, -1).toLowerCase();
// Some browsers yield DOMWindow for null and undefined, works fine on Node
if (type === 'domwindow' && !key) {
return key + '';
}
return type;
},
count:function() {
var n = 0;
for (var key in this._data) {
n++;
}
return n;
},
clear:function() {
// TODO: Would Object.create(null) make any difference
this._data = {};
},
hash:function(key) {
switch (this.type(key)) {
case 'undefined':
case 'null':
case 'boolean':
case 'number':
case 'regexp':
return key + '';
case 'date':
return ':' + key.getTime();
case 'string':
return '"' + key;
case 'array':
var hashes = [];
for (var i = 0; i < key.length; i++)
hashes[i] = this.hash(key[i]);
return '[' + hashes.join('|');
case 'object':
default:
// TODO: Don't use expandos when Object.defineProperty is not available?
if (!key._hmuid_) {
key._hmuid_ = ++HashMap.uid;
hide(key, '_hmuid_');
}
return '{' + key._hmuid_;
}
}
};
HashMap.uid = 0;
function hide(obj, prop) {
// Make non iterable if supported
if (Object.defineProperty) {
Object.defineProperty(obj, prop, {enumerable:false});
}
};
exports.HashMap = HashMap;
})(this.exports || this);