Skip to content

Instantly share code, notes, and snippets.

@uladkasach
Created July 8, 2023 07:54
Show Gist options
  • Save uladkasach/f4725262aa2c57526883a1df8e6ea4be to your computer and use it in GitHub Desktop.
Save uladkasach/f4725262aa2c57526883a1df8e6ea4be to your computer and use it in GitHub Desktop.
queue.ts
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