Website Summary Files Commits Branches @commit @diff @stats
path: root / homework / 45183 / CodeFormatting / input2.js
blob: c1c377c36e51e75c628940e0ca52a439097f5ca4 (plain) (blame)
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
export default class Queue {
    constructor() {
        this._firstNode = null;
        this._lastNode = null;
    }

    /**
     * Retrieves the first element in the queue.
     * It also removes it from the queue.
     * @returns {*}
     */
    dequeue() {
        if (!this._firstNode) {
            return this._firstNode;
        }

        const payload = this._firstNode.payload;

        this._firstNode = this._firstNode.next;

        return payload;
    }

    /**
     * Adds an item to the queue
     * @param {*} item
     */
    enqueue(item) {
        const newNode = {
            payload: item,
            next: null
        };

        if (this._firstNode === null) {
            this._firstNode = newNode;
            this._lastNode = newNode;

        } else {
            this._lastNode.next = newNode;
            this._lastNode = newNode;
        }
    }

    /**
     * Empties the queue
     */
    clear() {
        this._firstNode = null;
        this._lastNode = null;
    }

    /**
     * Gets the first element of the queue
     * @returns {*}
     */
    top() {
        if (!this._firstNode) {
            return this._firstNode;
        }

        return this._firstNode.payload;
    }

    /**
     * Checks whether the queue is empty or not
     * @returns {boolean}
     */
    isEmpty() {
        return !this._firstNode;
    }
}