MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / TripleStack

Class TripleStack

stacks/triple-stack.js:14–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12 * Additional space: push O(1), pop O(1), peek O(1)
13 */
14export class TripleStack {
15 constructor() {
16 this._array = [];
17 this._lengths = [0, 0, 0];
18 }
19
20 _getLength(stack) {
21 return this._lengths[stack - 1];
22 }
23
24 push(stack, value) {
25 let idx = this._getLength(stack) * 3 + stack - 1;
26 this._array[idx] = value;
27 ++this._lengths[stack - 1];
28 }
29
30 pop(stack) {
31 let length = this._getLength(stack),
32 value;
33 if (length > 0) {
34 let idx = (length - 1) * 3 + stack - 1;
35 value = this._array[idx];
36 this._array[idx] = undefined;
37 --this._lengths[stack - 1];
38 }
39 return value;
40 }
41
42 peek(stack) {
43 let length = this._getLength(stack),
44 value;
45 if (length > 0) {
46 let idx = (length - 1) * 3 + stack - 1;
47 value = this._array[idx];
48 }
49 return value;
50 }
51
52 isEmpty(stack) {
53 return this._getLength(stack) === 0;
54 }
55}
56
57const myTripleStack = new TripleStack();
58myTripleStack.push(3, 3);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected