asyncc
Version:
Just asynchronous patterns
79 lines (78 loc) • 1.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = PrioArray;
/**
* Creates an Array which adds items by priority
*/
function PrioArray() {
this.reset();
}
PrioArray.prototype = {
/**
* length of Array
*/
get length() {
return this.items.length;
},
/**
* shift item from array
* @return {Any} item
*/
shift: function shift() {
return (this.items.shift() || /* istanbul ignore next */{}).item;
},
/**
* push `item` to Array using priority
* @param {Any} item
* @param {Number} [prio=Infinity] - priority `0 ... Infinity` - lower values have higher priority
*/
push: function push(item, prio) {
var items = this.items;
if (typeof prio !== 'number') {
prio = Infinity;
items.push({
prio: prio,
item: item
});
} else {
var found;
prio = Math.abs(prio);
for (var i = 0; i < items.length; i++) {
if (prio < items[i].prio) {
items.splice(i, 0, {
prio: prio,
item: item
});
found = true;
break;
}
}
if (!found) {
items.push({
prio: prio,
item: item
});
}
}
return this;
},
/**
* unshift `item` to Array using priority
* @param {Any} item
*/
unshift: function unshift(item) {
this.items.unshift({
prio: 0,
item: item
});
return this;
},
/**
* removes all items in the Array
*/
reset: function reset() {
this.items = [];
}
};