forked from montagejs/collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic-set.js
89 lines (73 loc) · 2.47 KB
/
generic-set.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
module.exports = GenericSet;
function GenericSet() {
throw new Error("Can't construct. GenericSet is a mixin.");
}
GenericSet.prototype.isSet = true;
GenericSet.prototype.union = function (that) {
var union = this.constructClone(this);
union.addEach(that);
return union;
};
GenericSet.prototype.intersection = function (that) {
return this.constructClone(this.filter(function (value) {
return that.has(value);
}));
};
GenericSet.prototype.difference = function (that) {
var union = this.constructClone(this);
union.deleteEach(that);
return union;
};
GenericSet.prototype.symmetricDifference = function (that) {
var union = this.union(that);
var intersection = this.intersection(that);
return union.difference(intersection);
};
GenericSet.prototype.deleteAll = function (value) {
// deleteAll is equivalent to delete for sets since they guarantee that
// only one value exists for an equivalence class, but deleteAll returns
// the count of deleted values instead of whether a value was deleted.
return +this["delete"](value);
};
GenericSet.prototype.equals = function (that, equals) {
var self = this;
return (
that && typeof that.reduce === "function" &&
this.length === that.length &&
that.reduce(function (equal, value) {
return equal && self.has(value, equals);
}, true)
);
};
GenericSet.prototype.forEach = function (callback /*, thisp*/) {
var thisp = arguments[1];
return this.reduce(function (undefined, value, key, object, depth) {
//ECMASCRIPT Sets send value twice in callback to forEach
callback.call(thisp, value, value, object, depth);
}, undefined);
};
GenericSet.prototype.toJSON = function () {
return this.toArray();
};
// W3C DOMTokenList API overlap (does not handle variadic arguments)
GenericSet.prototype.contains = function (value) {
return this.has(value);
};
GenericSet.prototype.remove = function (value) {
return this["delete"](value);
};
GenericSet.prototype.toggle = function (value) {
if (this.has(value)) {
this["delete"](value);
} else {
this.add(value);
}
};
var _valuesArrayFunction = function(value,key) {return value;};
GenericSet.prototype.valuesArray = function() {
return this.map(_valuesArrayFunction);
}
var _entriesArrayFunction = function(value,key) {return [key,value];};
GenericSet.prototype.entriesArray = function() {
return this.map(_entriesArrayFunction);
}