What is the best way to implement a Stack and a Queue in JavaScript?
I'm looking to do the shunting-yard algorithm and I'm going to need these data-structures.
What is the best way to implement a Stack and a Queue in JavaScript?
I'm looking to do the shunting-yard algorithm and I'm going to need these data-structures.
Well in case someone else needs it you can use this NPM package https://www.npmjs.com/package/data-structures-typescript, it has a queue and also and stack, it supports both javascript and typescript and it's generic so you can use it with your own type of value ;)
Here is Map-based queue implementation for TypeScript.
export interface Queue<T> {
readonly length: number;
enqueue (item: T): T;
dequeue (): T | undefined;
peek (): T | undefined;
}
export class HashQueue<T> implements Queue<T> {
protected items: Map<number, T> = new Map();
protected headIndex = 0;
protected tailIndex = 0;
get length (): number {
return this.items.size;
}
enqueue (item: T): T {
const itemIndex = this.tailIndex++;
this.tailIndex >= Number.MAX_SAFE_INTEGER && (this.tailIndex = 0);
this.items.set(itemIndex, item);
return item;
}
dequeue (): T | undefined {
if (this.items.size) {
const itemIndex = this.headIndex++;
this.headIndex >= Number.MAX_SAFE_INTEGER && (this.headIndex = 0);
const result = this.items.get(itemIndex);
this.items.delete(itemIndex);
return result;
}
}
peek (): T | undefined {
return this.items.size ? this.items.get(this.headIndex) : undefined;
}
}
You can use this Queue class without any array You can get first and last element and is faster that javascript array.shift():
class Queue {
constructor() {
this.top = null;
this.bottom = null;
this._size = 0;
}
push(data) {
let newNode = new Node(data);
if (this.bottom == null) {
this.bottom = newNode;
}
if (this.top != null) {
this.top.next = newNode;
newNode.previous = this.top;
}
this.top = newNode;
this._size++;
}
pop() {
let data = null;
if (this.top != null) {
data = this.top.data;
this.top = this.top.previous;
if (this.top != null) {
this.top.next = null;
}else{
this.bottom= null;
}
this._size--;
}
return data;
}
last() {
return this.top ? this.top.data : null;
}
take() {
let data = null;
if (this.bottom != null) {
data = this.bottom.data;
this.bottom = this.bottom.next;
if (this.bottom != null) {
this.bottom.previous = null;
}else{
this.top = null;
}
this._size--;
}
return data;
}
first() {
return this.bottom ? this.bottom.data : null;
}
get size() {
return this._size;
}
}
class Node {
data=null;
constructor(data) {
this.next = null;
this.previous = null;
if(data){
this.data = data;
}
}
}