-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.js
81 lines (81 loc) · 1.51 KB
/
HashTable.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
function HashTable(obj){
this.hash = {};
this.total = 0;
this.load(obj);
}
HashTable.prototype = {
add : function(key, obj){
if(!(key in this.hash)){
this.total += 1;
} else {
console.log('The key [' + key + '] is overrided')
}
this.hash[key] = obj;
},
load : function(obj, creator){
if(!obj || typeof obj != 'object') return;
var p;
if(typeof creator != 'function'){
for(p in obj){
this.add(p, obj[p]);
}
} else {
for(p in obj){
this.add(p, creator(obj[p]));
}
}
p = null;
},
remove : function(key){
if(key in this.hash){
this.total -= 1;
return delete this.hash[key];
}
return false;
},
has : function(key){
return key in this.hash;
},
get : function(key){
return this.hash[key];
},
each : function(callback){
if(typeof callback != 'function') return;
var p, h = this.hash, i = 0;
for(p in h){
if(!!callback(h[p], p, h, i++)) break;
}
p = h = i = null;
},
map : function(callback){
if(typeof callback != 'function') return;
var arr = [];
this.each(function(n){
callback(n) && arr.push(n);
})
return arr;
},
every : function(callback){
if(typeof callback != 'function') return;
var b = true;
this.each(function(n){
if(!callback(n)){
b = false;
return true;
}
})
return b;
},
some : function(callback){
if(typeof callback != 'function') return;
var b = false;
this.each(function(n){
if(!!callback(n)){
b = true;
return true;
}
})
return b;
}
}
HashTable.prototype.$ = HashTable.prototype.get;