📦WaitingList
data structure ⟩ WaitingList
WaitingList
is used in breadth-first search / depth-first search (Graph).
replit ⟩ WaitingList (js), require ⟩ Stack, Queue.
const { Stack } = require('./Stack.js');
const { Queue } = require('./Queue.js');
// ⭐ WaitingList
// 2022.12.28 - ??:?? - first version
// ----------------------------
// 🔹 .enqueue(a, b, c ...) // speaks in Queue's language
// 🔹 .dequeue() // (same)
// 🔸 .first
// 🔸 .length
// 🔸 .isEmpty
// ----------------------------
// 🔹 .toString()
// 🔹 .log()
// 🔸 .debugInfo
// 🔸 .isStack
// 🔸 .isQueue
//
class WaitingList {
// 🔸 private members
#data; // a stack or queue
// ⭐ constructor
constructor(mode, ...elements) {
switch (mode) {
case 'stack': this.#data = new Stack(...elements); break;
case 'queue': this.#data = new Queue(...elements); break;
default: throw new Error(`WaitingList only accepts "stack" or "queue" mode.`);
}
}
// -----------------------------
// speak in Queue's language
// -----------------------------
enqueue(...elements) { this.#data.enqueue(...elements) }
dequeue() { return this.#data.dequeue() }
get first() { return this.#data.first } // 🔸 .first
get length() { return this.#data.length } // 🔸 .length
get isEmpty() { return this.#data.isEmpty } // 🔸 .isEmpty
toString() { return this.#data.toString() } // 🔹 .toString()
// -------------
// dubugging
// -------------
log() { this.#data.log() } // 🔹 .log()
get isStack() { return this.#data instanceof Stack } // 🔸 .isStack
get isQueue() { return this.#data instanceof Queue } // 🔸 .isQueue
get debugInfo() { return this.#data.debugInfo } // 🔸 .debugInfo
}
module.exports = { WaitingList };
'use strict'; // ⭐ toggle sloppy/strict mode
const { log } = console;
// ⭐ import
const { WaitingList } = require('./DataStructure/WaitingList.js');
// const q = new WaitingList('queue', 1, 2, 3); // ⭐ mode = 'queue'
const q = new WaitingList('stack', 1, 2, 3); // ⭐ mode = 'stack'
// ✅ execute commands
;[
// commands value Queue H T L | value Stack
// --------------------------------------------------------------------
`q`, // <- 1,2,3] 0 3 3 | [1,2,3 ->
`q.dequeue()`, // 1 <- 2,3] 1 3 2 | 3 [1,2
`q.first`, // 2 | 2
`q.dequeue()`, // 2 <- 3] 2 3 1 | 2 [1
`q.enqueue(4)`, // <- 3,4] 2 4 2 | [1,4
`q.dequeue()`, // 3 <- 4] 3 4 1 | 4 [1
`q.dequeue()`, // 4 <- ] 4 4 0 | 1 [
`q.dequeue()`, // null <- ] 4 4 0 | null [
`q.isEmpty`, // true | true
].forEach(cmd => {
log('-'.repeat(40));
log(`${cmd}`);
const value = eval(cmd); // execute command
if (!(value instanceof WaitingList)) { log(value); }
log(q.toString(), q.debugInfo);
});
Last updated