1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | 'use strict';
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | function has(object, key) {
|
23 | return Object.prototype.hasOwnProperty.call(object, key);
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | function Set(keyTransform) {
|
31 | this.values = Object.create(null);
|
32 | this.keyTransform = keyTransform;
|
33 | if (!this.keyTransform) {
|
34 | this.keyTransform = function (x) { return x; };
|
35 | }
|
36 | }
|
37 |
|
38 | Object.defineProperties(Set.prototype, {
|
39 | add: {
|
40 | value: function (x) {
|
41 | if (x.forEach) {
|
42 | return this.addRange(x);
|
43 | }
|
44 | if (arguments.length > 1) {
|
45 | return this.addRange(Array.prototype.slice.call(arguments, 0));
|
46 | }
|
47 | var key = this.keyTransform(x);
|
48 | this.values[key] = 1;
|
49 | return this;
|
50 | },
|
51 | },
|
52 |
|
53 | addRange: {
|
54 | value: function (values) {
|
55 | var self = this;
|
56 | values.forEach(function (x) {
|
57 | var key = self.keyTransform(x);
|
58 | self.values[key] = 1;
|
59 | });
|
60 | return self;
|
61 | }
|
62 | },
|
63 |
|
64 | has: {
|
65 | value: function (key) {
|
66 | return has(this.values, this.keyTransform(key));
|
67 | }
|
68 | },
|
69 |
|
70 | delete: {
|
71 | value: function (key) {
|
72 | var self = this;
|
73 | if (key.forEach) {
|
74 | key.forEach(function (k) { delete self.values[self.keyTransform(k)]; });
|
75 | } else if (arguments.length > 1) {
|
76 | return self.delete(Array.prototype.slice.call(arguments, 0));
|
77 | } else {
|
78 | delete self.values[self.keyTransform(key)];
|
79 | }
|
80 | return self;
|
81 | }
|
82 | },
|
83 |
|
84 | clear: {
|
85 | value: function () {
|
86 | this.values = Object.create(null);
|
87 | }
|
88 | },
|
89 |
|
90 | keys: {
|
91 | value: function () {
|
92 | return Object.keys(this.values);
|
93 | }
|
94 | },
|
95 |
|
96 | forEach: {
|
97 | value: function (callbackFn, thisArg) {
|
98 | this.keys().forEach(callbackFn, thisArg);
|
99 | }
|
100 | },
|
101 |
|
102 | map: {
|
103 | value: function (callbackFn, thisArg) {
|
104 | return this.keys().map(callbackFn, thisArg);
|
105 | }
|
106 | },
|
107 |
|
108 | size: {
|
109 | value: function () {
|
110 | return Object.keys(this.values).length;
|
111 | }
|
112 | }
|
113 | });
|
114 |
|
115 | module.exports = Set;
|