UNPKG

2.58 kBJavaScriptView Raw
1/**
2* Copyright (c) Microsoft. All rights reserved.
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7* http://www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14*/
15
16'use strict';
17
18//
19// Safe reference to static hasownproperty
20//
21
22function has(object, key) {
23 return Object.prototype.hasOwnProperty.call(object, key);
24}
25
26//
27// Yet another variant of a set in javascript
28//
29
30function 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
38Object.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
115module.exports = Set;