Easily Implement Stacks (Fifo) And Queues (Lifo) With JavaScript

I'm currently reviewing Javascript basis for a personnal project and it appears i often use stacks and queues implicitly. Let's make it explicit and easyer 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.

Queues : First In Firt Out

Here is 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 :

Stacks (Last In First Out)

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 !

< Blog