lib/goog/structs/set.js

1// Copyright 2006 The Closure Library Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
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 * @fileoverview Datastructure: Set.
17 *
18 * @author arv@google.com (Erik Arvidsson)
19 *
20 * This class implements a set data structure. Adding and removing is O(1). It
21 * supports both object and primitive values. Be careful because you can add
22 * both 1 and new Number(1), because these are not the same. You can even add
23 * multiple new Number(1) because these are not equal.
24 */
25
26
27goog.provide('goog.structs.Set');
28
29goog.require('goog.structs');
30goog.require('goog.structs.Collection');
31goog.require('goog.structs.Map');
32
33
34
35/**
36 * A set that can contain both primitives and objects. Adding and removing
37 * elements is O(1). Primitives are treated as identical if they have the same
38 * type and convert to the same string. Objects are treated as identical only
39 * if they are references to the same object. WARNING: A goog.structs.Set can
40 * contain both 1 and (new Number(1)), because they are not the same. WARNING:
41 * Adding (new Number(1)) twice will yield two distinct elements, because they
42 * are two different objects. WARNING: Any object that is added to a
43 * goog.structs.Set will be modified! Because goog.getUid() is used to
44 * identify objects, every object in the set will be mutated.
45 * @param {Array<T>|Object<?,T>=} opt_values Initial values to start with.
46 * @constructor
47 * @implements {goog.structs.Collection<T>}
48 * @final
49 * @template T
50 */
51goog.structs.Set = function(opt_values) {
52 this.map_ = new goog.structs.Map;
53 if (opt_values) {
54 this.addAll(opt_values);
55 }
56};
57
58
59/**
60 * Obtains a unique key for an element of the set. Primitives will yield the
61 * same key if they have the same type and convert to the same string. Object
62 * references will yield the same key only if they refer to the same object.
63 * @param {*} val Object or primitive value to get a key for.
64 * @return {string} A unique key for this value/object.
65 * @private
66 */
67goog.structs.Set.getKey_ = function(val) {
68 var type = typeof val;
69 if (type == 'object' && val || type == 'function') {
70 return 'o' + goog.getUid(/** @type {Object} */ (val));
71 } else {
72 return type.substr(0, 1) + val;
73 }
74};
75
76
77/**
78 * @return {number} The number of elements in the set.
79 * @override
80 */
81goog.structs.Set.prototype.getCount = function() {
82 return this.map_.getCount();
83};
84
85
86/**
87 * Add a primitive or an object to the set.
88 * @param {T} element The primitive or object to add.
89 * @override
90 */
91goog.structs.Set.prototype.add = function(element) {
92 this.map_.set(goog.structs.Set.getKey_(element), element);
93};
94
95
96/**
97 * Adds all the values in the given collection to this set.
98 * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection
99 * containing the elements to add.
100 */
101goog.structs.Set.prototype.addAll = function(col) {
102 var values = goog.structs.getValues(col);
103 var l = values.length;
104 for (var i = 0; i < l; i++) {
105 this.add(values[i]);
106 }
107};
108
109
110/**
111 * Removes all values in the given collection from this set.
112 * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection
113 * containing the elements to remove.
114 */
115goog.structs.Set.prototype.removeAll = function(col) {
116 var values = goog.structs.getValues(col);
117 var l = values.length;
118 for (var i = 0; i < l; i++) {
119 this.remove(values[i]);
120 }
121};
122
123
124/**
125 * Removes the given element from this set.
126 * @param {T} element The primitive or object to remove.
127 * @return {boolean} Whether the element was found and removed.
128 * @override
129 */
130goog.structs.Set.prototype.remove = function(element) {
131 return this.map_.remove(goog.structs.Set.getKey_(element));
132};
133
134
135/**
136 * Removes all elements from this set.
137 */
138goog.structs.Set.prototype.clear = function() {
139 this.map_.clear();
140};
141
142
143/**
144 * Tests whether this set is empty.
145 * @return {boolean} True if there are no elements in this set.
146 */
147goog.structs.Set.prototype.isEmpty = function() {
148 return this.map_.isEmpty();
149};
150
151
152/**
153 * Tests whether this set contains the given element.
154 * @param {T} element The primitive or object to test for.
155 * @return {boolean} True if this set contains the given element.
156 * @override
157 */
158goog.structs.Set.prototype.contains = function(element) {
159 return this.map_.containsKey(goog.structs.Set.getKey_(element));
160};
161
162
163/**
164 * Tests whether this set contains all the values in a given collection.
165 * Repeated elements in the collection are ignored, e.g. (new
166 * goog.structs.Set([1, 2])).containsAll([1, 1]) is True.
167 * @param {goog.structs.Collection<T>|Object} col A collection-like object.
168 * @return {boolean} True if the set contains all elements.
169 */
170goog.structs.Set.prototype.containsAll = function(col) {
171 return goog.structs.every(col, this.contains, this);
172};
173
174
175/**
176 * Finds all values that are present in both this set and the given collection.
177 * @param {Array<S>|Object<?,S>} col A collection.
178 * @return {!goog.structs.Set<T|S>} A new set containing all the values
179 * (primitives or objects) present in both this set and the given
180 * collection.
181 * @template S
182 */
183goog.structs.Set.prototype.intersection = function(col) {
184 var result = new goog.structs.Set();
185
186 var values = goog.structs.getValues(col);
187 for (var i = 0; i < values.length; i++) {
188 var value = values[i];
189 if (this.contains(value)) {
190 result.add(value);
191 }
192 }
193
194 return result;
195};
196
197
198/**
199 * Finds all values that are present in this set and not in the given
200 * collection.
201 * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection.
202 * @return {!goog.structs.Set} A new set containing all the values
203 * (primitives or objects) present in this set but not in the given
204 * collection.
205 */
206goog.structs.Set.prototype.difference = function(col) {
207 var result = this.clone();
208 result.removeAll(col);
209 return result;
210};
211
212
213/**
214 * Returns an array containing all the elements in this set.
215 * @return {!Array<T>} An array containing all the elements in this set.
216 */
217goog.structs.Set.prototype.getValues = function() {
218 return this.map_.getValues();
219};
220
221
222/**
223 * Creates a shallow clone of this set.
224 * @return {!goog.structs.Set<T>} A new set containing all the same elements as
225 * this set.
226 */
227goog.structs.Set.prototype.clone = function() {
228 return new goog.structs.Set(this);
229};
230
231
232/**
233 * Tests whether the given collection consists of the same elements as this set,
234 * regardless of order, without repetition. Primitives are treated as equal if
235 * they have the same type and convert to the same string; objects are treated
236 * as equal if they are references to the same object. This operation is O(n).
237 * @param {goog.structs.Collection<T>|Object} col A collection.
238 * @return {boolean} True if the given collection consists of the same elements
239 * as this set, regardless of order, without repetition.
240 */
241goog.structs.Set.prototype.equals = function(col) {
242 return this.getCount() == goog.structs.getCount(col) && this.isSubsetOf(col);
243};
244
245
246/**
247 * Tests whether the given collection contains all the elements in this set.
248 * Primitives are treated as equal if they have the same type and convert to the
249 * same string; objects are treated as equal if they are references to the same
250 * object. This operation is O(n).
251 * @param {goog.structs.Collection<T>|Object} col A collection.
252 * @return {boolean} True if this set is a subset of the given collection.
253 */
254goog.structs.Set.prototype.isSubsetOf = function(col) {
255 var colCount = goog.structs.getCount(col);
256 if (this.getCount() > colCount) {
257 return false;
258 }
259 // TODO(user) Find the minimal collection size where the conversion makes
260 // the contains() method faster.
261 if (!(col instanceof goog.structs.Set) && colCount > 5) {
262 // Convert to a goog.structs.Set so that goog.structs.contains runs in
263 // O(1) time instead of O(n) time.
264 col = new goog.structs.Set(col);
265 }
266 return goog.structs.every(this, function(value) {
267 return goog.structs.contains(col, value);
268 });
269};
270
271
272/**
273 * Returns an iterator that iterates over the elements in this set.
274 * @param {boolean=} opt_keys This argument is ignored.
275 * @return {!goog.iter.Iterator} An iterator over the elements in this set.
276 */
277goog.structs.Set.prototype.__iterator__ = function(opt_keys) {
278 return this.map_.__iterator__(false);
279};