main
Last change
on this file was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 4 days ago |
F4 Finalna Verzija
|
-
Property mode
set to
100644
|
File size:
1.4 KB
|
Rev | Line | |
---|
[79a0317] | 1 | /*
|
---|
| 2 | How it works:
|
---|
| 3 | `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | class Node {
|
---|
| 7 | value;
|
---|
| 8 | next;
|
---|
| 9 |
|
---|
| 10 | constructor(value) {
|
---|
| 11 | this.value = value;
|
---|
| 12 | }
|
---|
| 13 | }
|
---|
| 14 |
|
---|
| 15 | export default class Queue {
|
---|
| 16 | #head;
|
---|
| 17 | #tail;
|
---|
| 18 | #size;
|
---|
| 19 |
|
---|
| 20 | constructor() {
|
---|
| 21 | this.clear();
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | enqueue(value) {
|
---|
| 25 | const node = new Node(value);
|
---|
| 26 |
|
---|
| 27 | if (this.#head) {
|
---|
| 28 | this.#tail.next = node;
|
---|
| 29 | this.#tail = node;
|
---|
| 30 | } else {
|
---|
| 31 | this.#head = node;
|
---|
| 32 | this.#tail = node;
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | this.#size++;
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | dequeue() {
|
---|
| 39 | const current = this.#head;
|
---|
| 40 | if (!current) {
|
---|
| 41 | return;
|
---|
| 42 | }
|
---|
| 43 |
|
---|
| 44 | this.#head = this.#head.next;
|
---|
| 45 | this.#size--;
|
---|
| 46 | return current.value;
|
---|
| 47 | }
|
---|
| 48 |
|
---|
| 49 | peek() {
|
---|
| 50 | if (!this.#head) {
|
---|
| 51 | return;
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | return this.#head.value;
|
---|
| 55 |
|
---|
| 56 | // TODO: Node.js 18.
|
---|
| 57 | // return this.#head?.value;
|
---|
| 58 | }
|
---|
| 59 |
|
---|
| 60 | clear() {
|
---|
| 61 | this.#head = undefined;
|
---|
| 62 | this.#tail = undefined;
|
---|
| 63 | this.#size = 0;
|
---|
| 64 | }
|
---|
| 65 |
|
---|
| 66 | get size() {
|
---|
| 67 | return this.#size;
|
---|
| 68 | }
|
---|
| 69 |
|
---|
| 70 | * [Symbol.iterator]() {
|
---|
| 71 | let current = this.#head;
|
---|
| 72 |
|
---|
| 73 | while (current) {
|
---|
| 74 | yield current.value;
|
---|
| 75 | current = current.next;
|
---|
| 76 | }
|
---|
| 77 | }
|
---|
| 78 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.