Easily Implement Stacks (Fifo) And Queues (Lifo) With JavaScript
I'm currently reviewing Javascript basis for a personal project and it appears I often use stacks and queues implicitly. Let's make it explicit and easier to debug/use.
It's really easy to create queues (FIFO) by simply creating an Array and only use push and shift methods. The same for stacks (LIFO) with push and pop. But when coming back to the code or working together it can lead to hardly detectable bugs or unexpected behaviors. That's why I decided to implement them seriously with the help of the closure pattern. Let's dive in the code.
The tip is deadly simple, we're keeping a reference to the elements in the scope of our set of functions and the Queue instances expose only those functions as methods. So, we're sure our queues will be used properly.
If you're coding in a modern JavaScript engine you'll probably want to access the queue length as a property like it's done with arrays or strings. Here is the way to:
Now we can simply modify the above code to also manage stacks:
As you can see JavaScript closures allows you to easily create constructors using only a subset of an existing data type. Feel free to use or patch it!