×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Isaac Dettman
Added: Nov 26, 2016 6:08 PM
Views: 5
FIFO Array - first in first out
  1. function FifoArray(max, elements) {
  2.   // Error checking
  3.   if (!max)
  4.     throw new Error('no `max` value provided to FifoArray()');
  5.  
  6.   // Build the initial elements array
  7.   if (!elements)
  8.     elements = [];
  9.  
  10.   // Define the array to be returned
  11.   var array = Array.apply(null, []);
  12.  
  13.   // Map of methods to redefine
  14.   var redefines = [
  15.     {
  16.       prop: 'push',
  17.       trim: 'front'
  18.     },
  19.     {
  20.       prop: 'unshift',
  21.       trim: 'back'
  22.     },
  23.     {
  24.       prop: 'splice',
  25.       trim: 'back'
  26.     }
  27.   ];
  28.  
  29.   // Process the map
  30.   redefines.forEach(function (r) {
  31.     array[r.prop] = function () {
  32.       Array.prototype[r.prop].apply(this, arguments); // apply the original method
  33.       var trim = (r.trim == 'back') ? [this.max] : [0, this.length - max];
  34.       Array.prototype.splice.apply(this, trim);
  35.     };
  36.     Object.defineProperty(array, r.prop, {
  37.       enumerable: false
  38.     }); // hide it
  39.   });
  40.  
  41.   // Manage the .max property
  42.   Object.defineProperty(array, 'max', {
  43.     get: function () {
  44.       return max;
  45.     },
  46.     set: function (newMax) {
  47.       max = newMax;
  48.       while (this.length > this.max) this.pop(); // trim when necessary
  49.     },
  50.     enumerable: false // hide it
  51.   });
  52.  
  53.   // now that it's ready, populate the fifoArray with initial elements
  54.   elements.forEach(function (element) {
  55.     array.push(element);
  56.   });
  57.  
  58.   // mmm, bacon!
  59.   return array;
  60. };
  61.  
  62. module.exports = FifoArray;