-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhash.js
87 lines (77 loc) · 2.11 KB
/
hash.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
var Hash = Class.extend({
init: function init(sourceObj) {
this.length = 0;
this.items = {};
if (sourceObj instanceof Array) {
throw 'Initialising hash from array is not supported';
} else if (sourceObj instanceof Hash) {
sourceObj.each($.proxy(function (key, value) {
this.items[key] = value;
this.length++;
}, this));
} else if (sourceObj) {
$.each(sourceObj, $.proxy(function (key, value) {
if (sourceObj.hasOwnProperty(key)) {
this.items[key] = value;
this.length++;
}
}, this));
}
},
set: function set(key, value) {
var previous = undefined;
if (this.contains(key)) {
previous = this.items[key];
} else {
this.length++;
}
this.items[key] = value;
return previous;
},
contains: function contains(key) {
return this.items.hasOwnProperty(key);
},
get: function get(key) {
return this.contains(key) ? this.items[key] : undefined;
},
remove: function remove(key)
{
var previous = undefined;
if (this.contains(key)) {
previous = this.items[key];
this.length--;
delete(this.items[key]);
}
return previous;
},
clear: function clear()
{
this.items = {}
this.length = 0;
},
keys: function keys() {
var keys = [];
for (var key in this.items) {
if (this.contains(key)) {
keys.push(key);
}
}
return keys;
},
values: function values() {
var values = [];
for (var key in this.items) {
if (this.contains(key)) {
values.push(this.items[key]);
}
}
return values;
},
each: function each(callback) {
for (var key in this.items) {
if (this.contains(key)) {
callback(key, this.items[key]);
}
}
}
});