Skip to content

Instantly share code, notes, and snippets.

@diegolameira
Last active January 3, 2017 15:39
Show Gist options
  • Save diegolameira/0affaa4db3e3bfa39dfe to your computer and use it in GitHub Desktop.
Save diegolameira/0affaa4db3e3bfa39dfe to your computer and use it in GitHub Desktop.
Just a wrapper Class for FIFO, obviously Array.shift do the job standalone.
var FIFO = (function () {
'use strict';
// Load Dependencies
var _ = require('lodash');
// Set default configurations
var defaultConfig = {
type: 'number',
random: false,
priorityFrequency: 3,
}
// Constructor
function FIFO(type, random, priorityFrequency) {
this.items = [];
this._config = _.merge({}, defaultConfig, {
type: type,
random: random,
priorityFrequency: priorityFrequency,
});
this._priorityFrequencyCurrent = 0;
if (random)
this._nums = [];
}
Object.defineProperties(FIFO.prototype, {
'next': {
enumerable: false,
configurable: false,
get: next
},
'type': {
enumerable: false,
configurable: false,
get: function () {
return this._config.type;
}
},
'length': {
enumerable: false,
configurable: false,
get: function () {
return this.items.length
}
}
})
FIFO.prototype.add = add;
FIFO.prototype.get = get;
FIFO.prototype.list = list;
FIFO.prototype.remove = remove;
return FIFO;
///////////
function add(item) {
var _self = this;
// Converts to object
if (_.isString(item))
item = {value: item};
// Merge with a random or next id
_.merge(item, {
id: (function () {
var id,
last = _.last(_self.items) || {id:0};
if (_self._config.type === 'number')
id = !!_self._config.random ? randomGenerator(_self._nums) : last.id + 1;
else
id = item[_self._config.type] || item.value
return id;
}())
})
return this.items.push(item);
}
function get(idx) {
return !!idx ? this.remove(idx) : this.next;
}
function list() {
return this.items;
}
function remove(idx) {
return this.items.splice(idx, 1)[0];
}
function next() {
if (++this._priorityFrequencyCurrent < this._config.priorityFrequency)
return this.items.shift();
this._priorityFrequencyCurrent = 0;
var nextPriority = _.findWhere(this.items, {priority: true});
return this.get(this.items.indexOf(nextPriority));
}
function randomGenerator(nums) {
var rand = Math.floor((Math.random() * 999) + 1);
if (~nums.indexOf(rand))
return randomGenerator();
nums.push(rand);
return rand;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment