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.
The regular Array structure in Javascript is a Stack (first in, last out) and can also be used as a Queue (first in, first out) depending on the calls you make.
Check this link to see how to make an Array act like a Queue:
Queues
Or else you can use two arrays to implement queue data structure.
If I pop the elements now then the output will be 3,2,1. But we want FIFO structure so you can do the following.
Here is my Implementation of Stacks.
Here is a fairly simple queue implementation with two aims:
The stack implementation shares the second aim only.
Seems to me that the built in array is fine for a stack. If you want a Queue in TypeScript here is an implementation
And here is a
Jest
test for itHope someone finds this useful,
Cheers,
Stu
Javascript array shift() is slow especially when holding many elements. I know two ways to implement queue with amortized O(1) complexity.
First is by using circular buffer and table doubling. I have implemented this before. You can see my source code here https://github.com/kevyuu/rapid-queue
The second way is by using two stack. This is the code for queue with two stack
This is performance comparison using jsPerf
CircularQueue.shift() vs Array.shift()
http://jsperf.com/rapidqueue-shift-vs-array-shift
As you can see it is significantly faster with large dataset