-
Notifications
You must be signed in to change notification settings - Fork 43
/
array_mixins.js
114 lines (102 loc) · 2.31 KB
/
array_mixins.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
106
107
108
109
110
111
112
113
114
/* Array extensions that are in Javascript 1.6 */
/*
Array.prototype.forEach = function(fn)
{
for (var i=0;i<this.length;i++)
{
fn(this[i]);
}
}
Array.prototype.filter = function(fn)
{
r = [];
this.forEach(function (item) { if (fn(item)) r.push(item); });
return r;
}
Array.prototype.map = function(fn)
{
var r = [];
for (var i=0;i<this.length;i++)
{
r.push(fn(this[i]));
}
return r;
}
*/
Array.prototype.reduce = function(fn, initial)
{
var r, i;
// initial is optional, defaults to first item in list
initial ? r = initial : r = this[0];
for (i=1;i<this.length;i++)
{
r = fn(r, this[i]);
}
return r;
}
Array.prototype.copy = function(t)
{
r = [];
this.forEach(function (item) { r.push(item); });
return r;
}
Array.prototype.toHash = function()
{
// returns hash of { item : true, ... } for all unique items in array
var r = new Hashtable();
this.forEach(function (item) { r.put(item, true); });
return r;
}
Array.prototype.unique = function()
{
// s.unique() -->
// new array with unique elements of s
var h = {}; // use a hash-sieve
var r = [];
this.forEach(function (item) { h[item] = true; });
for (var item in h)
{
r.push(item);
}
return r;
}
Array.prototype.union = function(t)
{
// s.union(t) -->
// new set with elements from both s and t
return this.concat(t).unique();
}
Array.prototype.intersection = function(t)
{
// s.intersection(t) -->
// new array with elements common to s and t
var s = this.toHash();
var t = t.toHash();
var intersection = [];
s.keys().forEach(function(item)
{
if (t.containsKey(item))
intersection.push(item);
});
t.keys().forEach(function(item)
{
if (s.containsKey(item))
intersection.push(item);
});
return intersection;
}
Array.prototype.difference = function(t)
{
// s.difference(t) -->
// new array with elements in s but not in t
var t = t.toHash();
var r = [];
this.forEach(function (item) { if (!t.containsKey(item)) r.push(item); });
return r;
}
Array.prototype.symmetricDifference = function(t)
{
// s.symmetricDifference(t) -->
// new array with elements in either s or t but not both
return this.union(t).difference(this.intersection(t));
}