blob: 94afc792a16cb6fa8fc6a6ff2db5400dee0a319c (
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
|
/**
* An object that can be used as an array with a key
* Like PHP's array
* @template K
* @template V
*/
class ArrayWithKey {
/**
* All keys that are stored in the current object
* @type {K[]}
* @private
*/
__stack = [];
/**
* 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}
*/
push(key, value) {
this[key] = value;
this.__stack.push(key);
}
/**
* 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
*/
pop() {
let key = this.__stack.pop();
let prop = this[key];
delete this[key];
return prop;
}
/**
* Get the last key
* @returns {K|null} The last key, or null if the array is empty
*/
getLastKey() {
if (this.__stack.length === 0) {
return null;
}
return this.__stack[this.__stack.length - 1];
}
/**
* Get the first element
* @returns {{key:K,value:V}|null} The first element, or null if the array is empty
*/
shift() {
let key = this.__stack.shift();
let value = this[key];
delete this[key];
return {
key,
value,
};
}
/**
* Get the length of the array
* @returns {number} Amount of elements stored
*/
length() {
return this.__stack.length;
}
/**
* Get the last value
* @returns {V|null} The last element without removing it, or null if the array is empty
*/
last() {
let key = this.getLastKey();
if (key === null) {
return null;
}
return this[key];
}
}
module.exports = {
ArrayWithKey
};
|