github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/ui/app/utils/classes/rolling-array.js (about) 1 // An array with a max length. 2 // 3 // When max length is surpassed, items are removed from 4 // the front of the array. 5 6 // Native array methods 7 let { push, splice } = Array.prototype; 8 9 // Ember array prototype extension 10 let { insertAt } = Array.prototype; 11 12 // Using Classes to extend Array is unsupported in Babel so this less 13 // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes 14 export default function RollingArray(maxLength, ...items) { 15 const array = new Array(...items); 16 array.maxLength = maxLength; 17 18 // Bring the length back down to maxLength by removing from the front 19 array._limit = function() { 20 const surplus = this.length - this.maxLength; 21 if (surplus > 0) { 22 this.splice(0, surplus); 23 } 24 }; 25 26 array.push = function(...items) { 27 push.apply(this, items); 28 this._limit(); 29 return this.length; 30 }; 31 32 array.splice = function(...args) { 33 const returnValue = splice.apply(this, args); 34 this._limit(); 35 return returnValue; 36 }; 37 38 // All mutable array methods build on top of insertAt 39 array.insertAt = function(...args) { 40 const returnValue = insertAt.apply(this, args); 41 this._limit(); 42 this.arrayContentDidChange(); 43 return returnValue; 44 }; 45 46 array.unshift = function() { 47 throw new Error('Cannot unshift onto a RollingArray'); 48 }; 49 50 return array; 51 }