2023-08-31 14:19:21 -07:00
|
|
|
/**
|
|
|
|
* An object that can be used as an array with a key
|
|
|
|
* Like PHP's array
|
2023-09-07 00:42:44 -07:00
|
|
|
* @template K
|
|
|
|
* @template V
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
class ArrayWithKey {
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* All keys that are stored in the current object
|
|
|
|
* @type {K[]}
|
|
|
|
* @private
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
2023-09-07 00:42:44 -07:00
|
|
|
__stack = [];
|
2023-08-31 14:19:21 -07:00
|
|
|
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* Push an element to the end of the array
|
|
|
|
* @param {K} key The key of the element
|
|
|
|
* @param {V} value The value of the element
|
|
|
|
* @returns {void}
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
push(key, value) {
|
|
|
|
this[key] = value;
|
|
|
|
this.__stack.push(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* Get the last element and remove it from the array
|
|
|
|
* @returns {V|undefined} The first value, or undefined if there is no element to pop
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
pop() {
|
|
|
|
let key = this.__stack.pop();
|
|
|
|
let prop = this[key];
|
|
|
|
delete this[key];
|
|
|
|
return prop;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* Get the last key
|
|
|
|
* @returns {K|null} The last key, or null if the array is empty
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
getLastKey() {
|
|
|
|
if (this.__stack.length === 0) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return this.__stack[this.__stack.length - 1];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* Get the first element
|
|
|
|
* @returns {{key:K,value:V}|null} The first element, or null if the array is empty
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
shift() {
|
|
|
|
let key = this.__stack.shift();
|
|
|
|
let value = this[key];
|
|
|
|
delete this[key];
|
|
|
|
return {
|
|
|
|
key,
|
|
|
|
value,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* Get the length of the array
|
|
|
|
* @returns {number} Amount of elements stored
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
length() {
|
|
|
|
return this.__stack.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-09-07 00:42:44 -07:00
|
|
|
* Get the last value
|
|
|
|
* @returns {V|null} The last element without removing it, or null if the array is empty
|
2023-08-31 14:19:21 -07:00
|
|
|
*/
|
|
|
|
last() {
|
|
|
|
let key = this.getLastKey();
|
|
|
|
if (key === null) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return this[key];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
ArrayWithKey
|
|
|
|
};
|