Add Collection.keyArray/firstKey/lastKey/randomKey

This commit is contained in:
Schuyler Cebulskie
2016-09-12 21:39:41 -04:00
parent 84b33f9b66
commit ac85ffce4b
2 changed files with 41 additions and 2 deletions

File diff suppressed because one or more lines are too long

View File

@@ -5,7 +5,7 @@
class Collection extends Map {
/**
* Returns an ordered array of the values of this collection.
* @returns {array}
* @returns {Array}
* @example
* // identical to:
* Array.from(collection.values());
@@ -14,6 +14,17 @@ class Collection extends Map {
return Array.from(this.values());
}
/**
* Returns an ordered array of the keys of this collection.
* @returns {Array}
* @example
* // identical to:
* Array.from(collection.keys());
*/
keyArray() {
return Array.from(this.keys());
}
/**
* Returns the first item in this collection.
* @returns {*}
@@ -22,6 +33,14 @@ class Collection extends Map {
return this.values().next().value;
}
/**
* Returns the first key in this collection.
* @returns {*}
*/
firstKey() {
return this.keys().next().value;
}
/**
* Returns the last item in this collection. This is a relatively slow operation,
* since an array copy of the values must be made to find the last element.
@@ -32,6 +51,16 @@ class Collection extends Map {
return arr[arr.length - 1];
}
/**
* Returns the last key in this collection. This is a relatively slow operation,
* since an array copy of the keys must be made to find the last element.
* @returns {*}
*/
lastKey() {
const arr = this.keyArray();
return arr[arr.length - 1];
}
/**
* Returns a random item from this collection. This is a relatively slow operation,
* since an array copy of the values must be made to find a random element.
@@ -42,6 +71,16 @@ class Collection extends Map {
return arr[Math.floor(Math.random() * arr.length)];
}
/**
* Returns a random key from this collection. This is a relatively slow operation,
* since an array copy of the keys must be made to find a random element.
* @returns {*}
*/
randomKey() {
const arr = this.keyArray();
return arr[Math.floor(Math.random() * arr.length)];
}
/**
* If the items in this collection have a delete method (e.g. messages), invoke
* the delete method. Returns an array of promises