5.1. Priority Queues
Whenever pieces of data need to be arranged in order of priority, the typical solution is to use a priority queue. A standard queue is a first-in, first-out data structure: items are added at the back of the queue, wait in line, and eventually are removed from the front of the queue. A priority queue augments that methodology by inserting new values into the queue based on a priority, so a new value with a higher priority doesn't go to the back of the queue, but rather, gets inserted into an appropriate location. In a priority queue where 0 is the highest priority and 4 is the lowest, items with a priority of 3 will always be inserted into the queue before any items with a priority of 4. Likewise, items with a priority of 2 are inserted ahead of those with a priority of 3, and so on. This is the perfect paradigm for managing multiple XHR requests. Unfortunately, JavaScript doesn't have a built-in priority queue, so it's necessary to create one.
A generic priority queue can be made with a single Array object, making use of the built-in sort() method. When values are added to this custom priority queue, they are added to the array, which is then sorted. By providing a custom comparison function to the sort() method, it's possible to determine the order in which the values should appear within the array, making it perfect for assigning priorities. A comparison function has the following generic form:
function compare(oValue1, oValue2) { if (oValue1 < oValue2) ...
Get Professional Ajax, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.