Expand collection array caching

This commit is contained in:
Schuyler Cebulskie
2016-10-04 19:10:29 -04:00
parent 2c3c91fe41
commit 93425c3979
2 changed files with 25 additions and 19 deletions

File diff suppressed because one or more lines are too long

View File

@@ -3,36 +3,48 @@
* @extends {Map} * @extends {Map}
*/ */
class Collection extends Map { class Collection extends Map {
set(key, value) { constructor(iterable) {
super.set(key, value); super(iterable);
this.changed = true; this._array = null;
this._keyArray = null;
}
set(key, val) {
super.set(key, val);
this._array = null;
this._keyArray = null;
} }
delete(key) { delete(key) {
super.delete(key); super.delete(key);
this.changed = true; this._array = null;
this._keyArray = null;
} }
/** /**
* Returns an ordered array of the values of this collection. * Creates an ordered array of the values of this collection, and caches it internally. The array will only be
* reconstructed if an item is added to or removed from the collection, or if you add/remove elements on the array.
* @returns {Array} * @returns {Array}
* @example * @example
* // identical to: * // identical to:
* Array.from(collection.values()); * Array.from(collection.values());
*/ */
array() { array() {
return Array.from(this.values()); if (!this._array || this._array.length !== this.size) this._array = Array.from(this.values());
return this._array;
} }
/** /**
* Returns an ordered array of the keys of this collection. * Creates an ordered array of the keys of this collection, and caches it internally. The array will only be
* reconstructed if an item is added to or removed from the collection, or if you add/remove elements on the array.
* @returns {Array} * @returns {Array}
* @example * @example
* // identical to: * // identical to:
* Array.from(collection.keys()); * Array.from(collection.keys());
*/ */
keyArray() { keyArray() {
return Array.from(this.keys()); if (!this._keyArray || this._keyArray.length !== this.size) this._keyArray = Array.from(this.keys());
return this._keyArray;
} }
/** /**
@@ -77,11 +89,8 @@ class Collection extends Map {
* @returns {*} * @returns {*}
*/ */
random() { random() {
if (!this.cachedArray || this.cachedArray.length !== this.size || this.changed) { const arr = this.array();
this.cachedArray = this.array(); return arr[Math.floor(Math.random() * arr.length)];
this.changed = false;
}
return this.cachedArray[Math.floor(Math.random() * this.cachedArray.length)];
} }
/** /**
@@ -90,11 +99,8 @@ class Collection extends Map {
* @returns {*} * @returns {*}
*/ */
randomKey() { randomKey() {
if (!this.cachedKeyArray || this.cachedKeyArray.length !== this.size || this.changed) { const arr = this.keyArray();
this.cachedKeyArray = this.keyArray(); return arr[Math.floor(Math.random() * arr.length)];
this.changed = false;
}
return this.cachedKeyArray[Math.floor(Math.random() * this.cachedKeyArray.length)];
} }
/** /**