Thursday 11 December 2008

Javascript and Christmas Queues

Gentle reader , another JS pearl of wisdom.

Today I was writing some code and i needed to use a "stack" to take values in and feed them out one at a time using the "Last In First Out" or LIFO paradigm. Now you could should the urge overtake you go down the C++ or Java route and build all sorts of interesting data structures to do this. However there is an easy way using Arrays, let me explain

The javascript array object comes with a couple of interesting methods, namely push(), pop(), shift() and unshift() .

[array object].push([value]) appends a value to the bottom of an array

[array object].unshift([value]) does the same as the .push() method and appends a value to an array.

[array object].pop() removes the top most value from an array (index = 0)

[array object].shift() removes the bottom most value from an array (index array.length-1)

Using push() and pop() for LIFOing an array

var pileOfData = new Array();
// ** So we now have an empty array
pileOfData.push("Roast Turkey");
// ** The array has 1 element containing the string "Roast Turkey"
pileOfData.push("Christmas Pudding");
// ** The array now has 2 elements "Roast Turkey" and "Christmas Pudding"
var whatWasLastIn = pileOfData.pop();
// the pop() method gets the element at index 0 and removes it
// Now the array has one element "Christmas Pudding"
// and the variable whatWasLastIn contains "Roast Turkey"
Using push() and shift() for FIFOing an array
var pileOfData = new Array();
// ** So we now have an empty array
pileOfData.push("Roast Turkey");
// ** The array has 1 element containing the string "Roast Turkey"
pileOfData.push("Christmas Pudding");
// ** The array now has 2 elements "Roast Turkey" and "Christmas Pudding"
var whatWasLastIn = pileOfData.shift();
// the pop() method zips down to the bottom of the array and removes the element it finds there and removes it
// Now the array has one element "Roast Turkey"
// and the variable whatWasLastIn contains "Christmas Pudding"
I used the top method to queue AJAX requests and then release them to the server in a timely manner once the previous request had completed.

Disqus for Domi-No-Yes-Maybe