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.
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:
using only a subset of an existing data type. Feel free to use or patch it!