Implementing queue

ํ๋ฅผ ๊ฐ์ฒด๋กœ ์ƒ์„ฑํ•˜๊ณ  prorotype์„ ์‚ฌ์šฉํ•ด์„œ ๋ฉ”์„œ๋“œ๋ฅผ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.
๊ธฐ๋ณธ์ ์œผ๋กœ ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜๋ฉด ๋Œ€๋ถ€๋ถ„ ๋‹ค ๋Œ€์ฒด ๊ฐ€๋Šฅํ•ด์„œ ๋”ฐ๋กœ ๊ตฌํ˜„ํ•ด์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ํŽธ์ด์—ˆ๋Š”๋ฐ
์กฐ๊ธˆ ํŠน์ดํ•œ ์ ์ด getBuffer()๊ฐ™์ด ๊ฐ์ฒด ๋‚ด ๋ฐ์ดํ„ฐ์…‹์„ ๋ฐ˜ํ™˜(getter)ํ•˜๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.
// getBuffer(): ๊ฐ์ฒด ๋‚ด ๋ฐ์ดํ„ฐ ์…‹ ๋ฐ˜ํ™˜
Queue.prototype.getBuffer = function () {
    return this.array.slice();
};
notion image
๊ฐ์ฒด๊ฐ€ ๋ฐฐ์—ด๋งŒ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๊ทธ ๋ฐฐ์—ด๋งŒ ๊บผ๋‚ด์ฃผ๋ ค๊ณ  ์ด ๋ฉ”์„œ๋“œ๊ฐ€ ํ•„์š”ํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค.
๊ทธ๋Ÿผ ๋‹ค๋ฅธ ํ”„๋กœํผํ‹ฐ๋“ค์ด ์™œ ํ•„์š”ํ•œ๊ฐ€? ๋‚˜์ค‘์— ๋ณด๋ฉด ํ ์ตœ์ ํ™”๋ฅผ ์œ„ํ•ด ์‚ฌ์šฉ๋œ๋‹ค. ๋ฐฐ์—ด๋กœ ํ๋ฅผ ๋Œ€์ฒดํ•ด์„œ ์‚ฌ์šฉํ•  ๋•Œ ์„ฑ๋Šฅ์ด ๊ต‰์žฅํžˆ ๋Š๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋””ํ๋งŒ ์ƒ๊ฐํ•ด๋ด๋„ ๋งจ์•ž์˜ ์›์†Œ๋ฅผ ๊บผ๋‚ด๋Š”๋ฐ ๋ฐฐ์—ด์˜ ๋‚˜๋จธ์ง€ ์›์†Œ๋“ค์„ ๋Œ€๊ฑฐ ์ด๋™์‹œ์ผœ์•ผํ•˜๋Š” ์—ฐ์‚ฐ์ด ์ƒ๊ธด๋‹ค.
ย 
๋ณดํ†ต dequeue๋ฅผ shift() ๋ฉ”์„œ๋“œ๋กœ ๊ตฌํ˜„ํ•˜๊ณค ํ•˜๋Š”๋ฐ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฐ”๊ฟ”์ค„ ์ˆ˜ ์žˆ๋‹ค. ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋Š” ์œ ์ง€ํ•˜๊ณ  ๋ณ€ํ˜•ํ•˜์ง€ ์•Š์œผ๋ฉด์„œ delete๋กœ ์›์†Œ๊ฐ’๋งŒ ์‚ญ์ œ์‹œํ‚ค๊ณ  head์™€ tail๋กœ ์›์†Œ๊ฐ€ ์žˆ๋Š” ๋ฒ”์œ„๋งŒ ์žก์•„์ฃผ๋Š” ๋ฐฉ์‹์ด๋‹ค. ์ด ๋ฐฉ์‹์— ๋”ฐ๋ผ enqueue๋„ push() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋˜ ๋ฐฉ์‹์—์„œ tail ํ”„๋กœํผํ‹ฐ๋ฅผ ์‚ฌ์šฉํ•ด ๋„ฃ์–ด์ฃผ๋Š” ๋ฐฉ์‹์ด ๋œ๋‹ค.
Queue.prototype.enqueue = function (element) {
    return (this.array[this.tail++] = element);
};
Queue.prototype.dequeue = function () {
    if (this.tail === this.head) return undefined;

    let element = this.array[this.head];
    
let queue4 = new Queue([1, 2]);
console.log(queue4);

queue4.enqueue(3);
queue4.enqueue(4);
console.log(queue4);

console.log(queue4.dequeue());
console.log(queue4.dequeue());
console.log(queue4);
notion image
ย 
enqueue์™€ dequeue์—์„œ ์ถ”๊ฐ€๋˜๋Š” ๋ฐฉ์‹์— ๋Œ€ํ•ด์„œ๋งŒ ์ž˜ ์ดํ•ดํ•˜๋ฉด ์ข‹๋‹ค.
ย 
ย