-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayStackQueue.js
More file actions
96 lines (82 loc) · 2.09 KB
/
Copy patharrayStackQueue.js
File metadata and controls
96 lines (82 loc) · 2.09 KB
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
92
93
94
95
96
class Collection {
#arr;
constructor(...args) {
// console.log(args, [...args], ...args);
this.#arr = Array.isArray(args[0]) ? args[0] : [...args];
// console.log(this.#arr);
}
push(val) {
this.#arr.push(val);
}
pop() {
return this.#arr.pop();
}
shift() {
return this.#arr.shift();
}
clear() {
this.#arr.length = 0;
}
get peek() {
if (this.constructor.name === 'Stack') return this.#arr[this.length - 1];
return this.#arr[0];
}
get isEmpty() {
return !this.#arr.length;
}
get length() {
return this.#arr.length;
}
// [Symbol.iterator]() {
// let idx = -1;
// return {
// next: () => {
// idx += 1;
// return { value: this.#arr[idx], done : !this.#arr[idx] }
// },
// };
// }
*[Symbol.iterator]() {
for (let idx = 0; idx < this.#arr.length; idx += 1) {
yield this.#arr[idx];
}
}
toArray() {
return [...this.#arr];
}
print(cb) {
if (cb) {
cb([...this.#arr].reverse());
return;
}
console.log('coll>>', this.#arr);
}
}
class Stack extends Collection {
print() {
super.print(arr => console.log('STACK>>\n', arr.join('\n ')));
}
}
class Queue extends Collection {
enqueue(val) {
super.push(val);
}
dequeue() {
return super.shift();
}
print() {
super.print(arr => console.log('QUEUE>> ->', arr.join(' -> '), '->'));
}
}
const stack = new Stack([1, 2]); // or new Stack([1,2]); // (1,2)
stack.push(3); // 추가하기
console.log('spop>>>', stack.pop()); // 마지막에 추가된 하나 꺼내기
stack.push(3);
const queue = new Queue([11, 22]);
queue.enqueue(33); // 추가하기
console.log('deq>>', queue.dequeue()); // 추가한지 가장 오래된 - 먼저 들어간 - 하나 꺼내기
queue.enqueue(44);
// console.log('speek=', stack.peek);
// console.log('qpeek=', queue.peek);
stack.print();
queue.print();