Created
July 8, 2023 07:54
-
-
Save uladkasach/f4725262aa2c57526883a1df8e6ea4be to your computer and use it in GitHub Desktop.
queue.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export enum QueueType { | |
FIRST_IN_FIRST_OUT = "FIRST_IN_FIRST_OUT", | |
LAST_IN_FIRST_OUT = "LAST_IN_FIRST_OUT", | |
} | |
export class Queue<T> { | |
private type: QueueType; | |
private data: T[]; | |
constructor({ type = QueueType.LAST_IN_FIRST_OUT }: { type: QueueType }) { | |
this.type = type; | |
this.data = []; // clear it out | |
} | |
public push = (item: T) => { | |
this.data.push(item); | |
}; | |
public pop = () => { | |
// handle fifo | |
if (this.type === QueueType.FIRST_IN_FIRST_OUT) { | |
const [firstItem, ...otherItems] = this.data; | |
this.data = otherItems; | |
return firstItem; | |
} | |
// handle lifo | |
if (this.type === QueueType.LAST_IN_FIRST_OUT) { | |
const lastItem = this.data.slice(-1)[0]; | |
this.data = this.data.slice(0, -1); | |
return lastItem; | |
} | |
// if the above didn't handle it, probably an error | |
throw new Error("unexpected queue type"); | |
}; | |
public popAll = () => { | |
const items = this.data; | |
this.data = []; | |
return items; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment