-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.js
87 lines (73 loc) · 2.28 KB
/
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
/**
* @see https://github.com/tc39/proposal-set-methods
*/
'use strict';
const TYPE_ERR_MSG = 'Expected a set-like object.';
const SET_METHODS = ['has', 'keys'];
const SET_PROPS = ['size'];
const isSet = thing => thing instanceof Set;
const isSetLike = thing => isSet(thing) || (
typeof thing === 'object'
&& thing !== null
&& SET_METHODS.every(method => thing[method] instanceof Function)
&& SET_PROPS.every(prop => prop in thing)
);
if (! (Set.prototype.intersection instanceof Function)) {
Set.prototype.intersection = function intersection(set) {
if (! isSetLike(set)) {
throw new TypeError(TYPE_ERR_MSG);
}
return new Set([...this].filter(item => set.has(item)));
};
}
if (! (Set.prototype.difference instanceof Function)) {
Set.prototype.difference = function difference(set) {
if (! isSetLike(set)) {
throw new TypeError(TYPE_ERR_MSG);
}
return new Set([...this].filter(item => ! set.has(item)));
};
}
if (! (Set.prototype.union instanceof Function)) {
Set.prototype.union = function union(set) {
return new Set([...this, ...set]);
};
}
if (! (Set.prototype.isSubsetOf instanceof Function)) {
Set.prototype.isSubsetOf = function isSubsetOf(set) {
if (! isSetLike(set)) {
throw new TypeError(TYPE_ERR_MSG);
}
return [...this].every(item => set.has(item));
};
}
if (! (Set.prototype.isSupersetOf instanceof Function)) {
Set.prototype.isSupersetOf = function isSupersetOf(set) {
if (! isSetLike(set)) {
throw new TypeError(TYPE_ERR_MSG);
}
// @TODO Handle when `set` is set-like
return isSet(set)
? set.isSubsetOf(this)
: new Set(set.keys()).isSubsetOf(this);
};
}
if (! (Set.prototype.symmetricDifference instanceof Function)) {
Set.prototype.symmetricDifference = function symmetricDifference(set) {
if (! isSetLike(set)) {
throw new TypeError(TYPE_ERR_MSG);
}
// @TODO Handle when `set` is set-like
return isSet(set)
? new Set([...this.difference(set), ...set.difference(this)])
: new Set([...this.difference(set), ...new Set(set.keys()).difference(this)]);
};
}
if (! (Set.prototype.isDisjointFrom instanceof Function)) {
Set.prototype.isDisjointFrom = function isDisjointFrom(set) {
if (! isSetLike(set)) {
throw new TypeError(TYPE_ERR_MSG);
}
return new Set([...this, ...set]).size === this.size + set.size;
};
}