aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/labs/structs/map.js
blob: 0c030d838a51f6503d9cdd4964cb355d0faa8765 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview A map data structure that offers a convenient API to
 * manipulate a key, value map. The key must be a string.
 *
 * This implementation also ensure that you can use keys that would
 * not be usable using a normal object literal {}. Some examples
 * include __proto__ (all newer browsers), toString/hasOwnProperty (IE
 * <= 8).
 */

goog.provide('goog.labs.structs.Map');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.labs.object');
goog.require('goog.object');



/**
 * Creates a new map.
 * @constructor
 */
goog.labs.structs.Map = function() {
  // clear() initializes the map to the empty state.
  this.clear();
};


/**
 * @type {function(this: Object, string): boolean}
 * @private
 */
goog.labs.structs.Map.objectPropertyIsEnumerable_ =
    Object.prototype.propertyIsEnumerable;


/**
 * @type {function(this: Object, string): boolean}
 * @private
 */
goog.labs.structs.Map.objectHasOwnProperty_ =
    Object.prototype.hasOwnProperty;


/**
 * Primary backing store of this map.
 * @type {!Object}
 * @private
 */
goog.labs.structs.Map.prototype.map_;


/**
 * Secondary backing store for keys. The index corresponds to the
 * index for secondaryStoreValues_.
 * @type {!Array.<string>}
 * @private
 */
goog.labs.structs.Map.prototype.secondaryStoreKeys_;


/**
 * Secondary backing store for keys. The index corresponds to the
 * index for secondaryStoreValues_.
 * @type {!Array.<*>}
 * @private
 */
goog.labs.structs.Map.prototype.secondaryStoreValues_;


/**
 * Adds the (key, value) pair, overriding previous entry with the same
 * key, if any.
 * @param {string} key The key.
 * @param {*} value The value.
 */
goog.labs.structs.Map.prototype.set = function(key, value) {
  this.assertKeyIsString_(key);

  var newKey = !this.hasKeyInPrimaryStore_(key);
  this.map_[key] = value;

  // __proto__ is not settable on object.
  if (key == '__proto__' ||
      // Shadows for built-in properties are not enumerable in IE <= 8 .
      (!goog.labs.structs.Map.BrowserFeature.OBJECT_CREATE_SUPPORTED &&
       !goog.labs.structs.Map.objectPropertyIsEnumerable_.call(
           this.map_, key))) {
    delete this.map_[key];
    var index = goog.array.indexOf(this.secondaryStoreKeys_, key);
    if ((newKey = index < 0)) {
      index = this.secondaryStoreKeys_.length;
    }

    this.secondaryStoreKeys_[index] = key;
    this.secondaryStoreValues_[index] = value;
  }

  if (newKey) this.count_++;
};


/**
 * Gets the value for the given key.
 * @param {string} key The key whose value we want to retrieve.
 * @param {*=} opt_default The default value to return if the key does
 *     not exist in the map, default to undefined.
 * @return {*} The value corresponding to the given key, or opt_default
 *     if the key does not exist in this map.
 */
goog.labs.structs.Map.prototype.get = function(key, opt_default) {
  this.assertKeyIsString_(key);

  if (this.hasKeyInPrimaryStore_(key)) {
    return this.map_[key];
  }

  var index = goog.array.indexOf(this.secondaryStoreKeys_, key);
  return index >= 0 ? this.secondaryStoreValues_[index] : opt_default;
};


/**
 * Removes the map entry with the given key.
 * @param {string} key The key to remove.
 * @return {boolean} True if the entry is removed.
 */
goog.labs.structs.Map.prototype.remove = function(key) {
  this.assertKeyIsString_(key);

  if (this.hasKeyInPrimaryStore_(key)) {
    this.count_--;
    delete this.map_[key];
    return true;
  } else {
    var index = goog.array.indexOf(this.secondaryStoreKeys_, key);
    if (index >= 0) {
      this.count_--;
      goog.array.removeAt(this.secondaryStoreKeys_, index);
      goog.array.removeAt(this.secondaryStoreValues_, index);
      return true;
    }
  }
  return false;
};


/**
 * Adds the content of the map to this map. If a new entry uses a key
 * that already exists in this map, the existing key is replaced.
 * @param {!goog.labs.structs.Map} map The map to add.
 */
goog.labs.structs.Map.prototype.addAll = function(map) {
  goog.array.forEach(map.getKeys(), function(key) {
    this.set(key, map.get(key));
  }, this);
};


/**
 * @return {boolean} True if the map is empty.
 */
goog.labs.structs.Map.prototype.isEmpty = function() {
  return !this.count_;
};


/**
 * @return {number} The number of the entries in this map.
 */
goog.labs.structs.Map.prototype.getCount = function() {
  return this.count_;
};


/**
 * @param {string} key The key to check.
 * @return {boolean} True if the map contains the given key.
 */
goog.labs.structs.Map.prototype.containsKey = function(key) {
  this.assertKeyIsString_(key);
  return this.hasKeyInPrimaryStore_(key) ||
      goog.array.contains(this.secondaryStoreKeys_, key);
};


/**
 * Whether the map contains the given value. The comparison is done
 * using !== comparator. Also returns true if the passed value is NaN
 * and a NaN value exists in the map.
 * @param {*} value Value to check.
 * @return {boolean} True if the map contains the given value.
 */
goog.labs.structs.Map.prototype.containsValue = function(value) {
  var found = goog.object.some(this.map_, function(v, k) {
    return this.hasKeyInPrimaryStore_(k) &&
        goog.labs.object.is(v, value);
  }, this);
  return found || goog.array.contains(this.secondaryStoreValues_, value);
};


/**
 * @return {!Array.<string>} An array of all the keys contained in this map.
 */
goog.labs.structs.Map.prototype.getKeys = function() {
  var keys;
  if (goog.labs.structs.Map.BrowserFeature.OBJECT_KEYS_SUPPORTED) {
    keys = goog.array.clone(Object.keys(this.map_));
  } else {
    keys = [];
    for (var key in this.map_) {
      if (goog.labs.structs.Map.objectHasOwnProperty_.call(this.map_, key)) {
        keys.push(key);
      }
    }
  }

  goog.array.extend(keys, this.secondaryStoreKeys_);
  return keys;
};


/**
 * @return {!Array.<*>} An array of all the values contained in this map.
 *     There may be duplicates.
 */
goog.labs.structs.Map.prototype.getValues = function() {
  var values = [];
  var keys = this.getKeys();
  for (var i = 0; i < keys.length; i++) {
    values.push(this.get(keys[i]));
  }
  return values;
};


/**
 * @return {!Array.<Array>} An array of entries. Each entry is of the
 *     form [key, value]. Do not rely on consistent ordering of entries.
 */
goog.labs.structs.Map.prototype.getEntries = function() {
  var entries = [];
  var keys = this.getKeys();
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    entries.push([key, this.get(key)]);
  }
  return entries;
};


/**
 * Clears the map to the initial state.
 */
goog.labs.structs.Map.prototype.clear = function() {
  this.map_ = goog.labs.structs.Map.BrowserFeature.OBJECT_CREATE_SUPPORTED ?
      Object.create(null) : {};
  this.secondaryStoreKeys_ = [];
  this.secondaryStoreValues_ = [];
  this.count_ = 0;
};


/**
 * Clones this map.
 * @return {!goog.labs.structs.Map} The clone of this map.
 */
goog.labs.structs.Map.prototype.clone = function() {
  var map = new goog.labs.structs.Map();
  map.addAll(this);
  return map;
};


/**
 * @param {string} key The key to check.
 * @return {boolean} True if the given key has been added successfully
 *     to the primary store.
 * @private
 */
goog.labs.structs.Map.prototype.hasKeyInPrimaryStore_ = function(key) {
  // New browsers that support Object.create do not allow setting of
  // __proto__. In other browsers, hasOwnProperty will return true for
  // __proto__ for object created with literal {}, so we need to
  // special case it.
  if (key == '__proto__') {
    return false;
  }

  if (goog.labs.structs.Map.BrowserFeature.OBJECT_CREATE_SUPPORTED) {
    return key in this.map_;
  }

  return goog.labs.structs.Map.objectHasOwnProperty_.call(this.map_, key);
};


/**
 * Asserts that the given key is a string.
 * @param {string} key The key to check.
 * @private
 */
goog.labs.structs.Map.prototype.assertKeyIsString_ = function(key) {
  goog.asserts.assert(goog.isString(key), 'key must be a string.');
};


/**
 * Browser feature enum necessary for map.
 * @enum {boolean}
 */
goog.labs.structs.Map.BrowserFeature = {
  // TODO(user): Replace with goog.userAgent detection.
  /**
   * Whether Object.create method is supported.
   */
  OBJECT_CREATE_SUPPORTED: !!Object.create,

  /**
   * Whether Object.keys method is supported.
   */
  OBJECT_KEYS_SUPPORTED: !!Object.keys
};