JS 엔진은 큐를 가지고있다.
JS 동작원리 중 스택을 실행 하기 위해 큐를 사용한다.(Callback Queue)
데이터를 순차적으로 처리함.
사용 예로는 티켓예매 사이트를 예로 들수있다
티켓을 예매하기 위해 우선적으로 예매 버튼을 클릭한 사람에게 판매할수있는..?
선입선출 (FIFO)!!
const queue = [1, 2, 3, 4];
console.log(queue.shift()); // 1 (제거된 값)
console.log(queue); // [2, 3, 4]
✅ 장점: 간단하고 코드가 직관적임
⚠️ 단점: 배열 요소 이동으로 시간 복잡도 O(n)
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
return this.items.shift();
}
front() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
✅ 장점: 코드가 간단하고 이해하기 쉬움
⚠️ 단점: 대규모 데이터 처리 시 비효율적
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedListQueue {
constructor() {
this.front = null;
this.rear = null;
}
enqueue(value) {
const newNode = new Node(value);
if (!this.front) this.front = newNode;
else this.rear.next = newNode;
this.rear = newNode;
}
dequeue() {
if (!this.front) return null;
const value = this.front.value;
this.front = this.front.next;
if (!this.front) this.rear = null;
return value;
}
}
✅ 장점: 삽입과 삭제 시 빠름
⚠️ 단점: 메모리 사용량 증가
function simpleHash(key, size) {
let hashValue = 0;
for (let char of key) {
hashValue += char.charCodeAt(0);
}
return hashValue % size;
}
hash = key % tableSize
hash = floor((key * A) % 1 * tableSize)
class HashTable {
constructor(size = 50) {
this.table = new Array(size);
}
hash(key) {
let hashValue = 0;
for (let char of key) {
hashValue += char.charCodeAt(0);
}
return hashValue % this.table.length;
}
set(key, value) {
const index = this.hash(key);
if (!this.table[index]) {
this.table[index] = [];
}
this.table[index].push([key, value]);
}
get(key) {
const index = this.hash(key);
if (this.table[index]) {
for (let [storedKey, value] of this.table[index]) {
if (storedKey === key) return value;
}
}
return undefined;
}
}
✅ 장점: 충돌 처리 시 연결 리스트 사용으로 유연함
⚠️ 단점: 추가 메모리 사용
class OpenAddressHashTable {
constructor(size = 50) {
this.table = new Array(size).fill(null);
}
hash(key) {
let hashValue = 0;
for (let char of key) {
hashValue += char.charCodeAt(0);
}
return hashValue % this.table.length;
}
set(key, value) {
let index = this.hash(key);
while (this.table[index] !== null) {
index = (index + 1) % this.table.length; // 선형 탐사
}
this.table[index] = [key, value];
}
get(key) {
let index = this.hash(key);
while (this.table[index] !== null) {
if (this.table[index][0] === key) return this.table[index][1];
index = (index + 1) % this.table.length;
}
return undefined;
}
}
✅ 장점: 추가 데이터 구조 필요 없음
⚠️ 단점: 탐색 시간 증가 가능성