Class: SortedLoopArray

pc.SortedLoopArray

Helper class used to hold an array of items in a specific order. This array is safe to modify while we loop through it. The class assumes that it holds objects that need to be sorted based on one of their fields.

Constructor

(private) new SortedLoopArray(args)

Parameters:
Name Type Description
args Object Arguments
Properties
Name Type Description
sortBy String The name of the field that each element in the array is going to be sorted by
Properties:
Name Type Description
loopIndex Number The current index used to loop through the array. This gets modified if we add or remove elements from the array while looping. See the example to see how to loop through this array.
length Number The number of elements in the array.
items Array.<Object> The internal array that holds the actual array elements.
Source:
Example
var array = new pc.SortedLoopArray({ sortBy: 'priority' });
array.insert(item); // adds item to the right slot based on item.priority
array.append(item); // adds item to the end of the array
array.remove(item); // removes item from array
for (array.loopIndex = 0; array.loopIndex < array.length; array.loopIndex++) {
  // do things with array elements
  // safe to remove and add elements into the array while looping
}

Methods

(private) _binarySearch(item) → {Number}

Searches for the right spot to insert the specified item
Parameters:
Name Type Description
item Object The item
Source:
Returns:
The index where to insert the item
Type
Number

(private) append(item)

Appends the specified item to the end of the array. Faster than insert() as it does not binary search for the right index. This also adjusts the loopIndex accordingly.
Parameters:
Name Type Description
item Object The item to append
Source:

(private) insert(item)

Inserts the specified item into the array at the right index based on the 'sortBy' field passed into the constructor. This also adjusts the loopIndex accordingly.
Parameters:
Name Type Description
item Object The item to insert
Source:

(private) remove(item)

Removes the specified item from the array.
Parameters:
Name Type Description
item Object The item to remove
Source:

(private) sort()

Sorts elements in the array based on the 'sortBy' field passed into the constructor. This also updates the loopIndex if we are currently looping. WARNING: Be careful if you are sorting while iterating because if after sorting the array element that you are currently processing is moved behind other elements then you might end up iterating over elements more than once!
Source: