๐ฆ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