-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.js
91 lines (83 loc) · 2.19 KB
/
Queue.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class QueueNode {
constructor(value) {
this._value = value;
this._next = null;
}
}
class Queue {
constructor() {
this._first = null;
this._last = null;
this._size = 0;
}
get size() {
return this._size;
}
isEmpty() {
return this.size === 0;
}
enqueue(value) {
const oldLast = this._last;
this._last = new QueueNode(value);
if (this.isEmpty()) {
this._first = this._last;
} else {
oldLast._next = this._last;
}
this._size += 1;
return value;
}
dequeue() {
if (this.isEmpty()) {
this._last = null;
return null;
}
let deletedValue = this._first._value;
this._first = this._first._next;
this._size -= 1;
return deletedValue;
}
data() {
if (this._first === null) {
console.log('Queue: empty!');
return;
}
let arrQueue = [];
function logData(dataQueue) {
if (dataQueue !== null) {
arrQueue.push(dataQueue._value);
logData(dataQueue._next);
}
}
logData(this._first);
console.log('Queue: ');
arrQueue.forEach(node => console.log(node));
arrQueue = null;
}
}
const queue = new Queue();
console.log(`1 in -> ${queue.enqueue(1)}`);
console.log(`2 in -> ${queue.enqueue(true)}`);
console.log(`3 in -> ${queue.enqueue(null)}`);
console.log(`4 in -> ${queue.enqueue(undefined)}`);
console.log(`5 in -> ${queue.enqueue('string')}`);
console.log(`6 in -> ${queue.enqueue({ name: 'object' })}`);
console.log(`7 in -> ${queue.enqueue([1, 2, 3])}`);
console.log(`8 in -> ${queue.enqueue(function func() {})}`);
console.log('-'.repeat(25));
queue.data();
console.log('-'.repeat(25));
console.log('размер очереди:', queue.size);
console.log('-'.repeat(25));
console.log(`1 out -> ${queue.dequeue()}`);
console.log(`2 out -> ${queue.dequeue()}`);
console.log(`3 out -> ${queue.dequeue()}`);
console.log(`4 out -> ${queue.dequeue()}`);
console.log(`5 out -> ${queue.dequeue()}`);
console.log(`6 out -> ${queue.dequeue()}`);
console.log(`7 out -> ${queue.dequeue()}`);
console.log(`8 out -> ${queue.dequeue()}`);
console.log('-'.repeat(25));
queue.data();
console.log('-'.repeat(25));
console.log('размер очереди:', queue.size);