Tuesday, March 20, 2007

Arrays as Multipurpose Data Structures

Although that JavaScript may seem limited on the data structure front at first glance, its Array class is much more versatile than the usual array type found in other programming languages (like C++ or Java). It's commonly used as an array or associative array, and this tip demonstrates how to use it as a stack, queue. Re-using the Array class instead of writing such data structures provides two benefits: First, time isn't wasted rewriting existing functionality, and second, the built-in browser implementation will be more efficient than its JavaScript counterpart.

Stack

A stack follows the Last-In First-Out (LIFO) paradigm: an item added last will be removed first. The Array class has 2 methods that provide stack functionality. they are push() and pop(). push() appends an item to the end of the array, and pop() removes and returns the last item in the array. The next code block demonstrates how to utilize each of them:

Eg:

var stack = [];
stack.push(2); // stack is now [2]
stack.push(5); // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i); // displays 5

Queue
A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item. let's see how to use them:

Eg:

var queue = [];
queue.push(2); // queue is now [2]
queue.push(5); // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
alert(i); // displays 2

No comments: