2018-08-30 00:14:57 +00:00
|
|
|
// An array with a max length.
|
|
|
|
//
|
|
|
|
// When max length is surpassed, items are removed from
|
|
|
|
// the front of the array.
|
|
|
|
|
2018-09-14 16:38:17 +00:00
|
|
|
// Native array methods
|
|
|
|
let { push, splice } = Array.prototype;
|
|
|
|
|
|
|
|
// Ember array prototype extension
|
|
|
|
let { insertAt } = Array.prototype;
|
|
|
|
|
2018-08-30 00:14:57 +00:00
|
|
|
// Using Classes to extend Array is unsupported in Babel so this less
|
|
|
|
// ideal approach is taken: https://babeljs.io/docs/en/caveats#classes
|
|
|
|
export default function RollingArray(maxLength, ...items) {
|
|
|
|
const array = new Array(...items);
|
|
|
|
array.maxLength = maxLength;
|
|
|
|
|
2018-09-14 15:57:26 +00:00
|
|
|
// Bring the length back down to maxLength by removing from the front
|
|
|
|
array._limit = function() {
|
2018-08-30 00:14:57 +00:00
|
|
|
const surplus = this.length - this.maxLength;
|
|
|
|
if (surplus > 0) {
|
|
|
|
this.splice(0, surplus);
|
|
|
|
}
|
2018-09-14 15:57:26 +00:00
|
|
|
};
|
2018-08-30 00:14:57 +00:00
|
|
|
|
2018-09-14 15:57:26 +00:00
|
|
|
array.push = function(...items) {
|
2018-09-14 16:38:17 +00:00
|
|
|
push.apply(this, items);
|
2018-09-14 15:57:26 +00:00
|
|
|
this._limit();
|
|
|
|
return this.length;
|
2018-08-30 00:14:57 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
array.splice = function(...args) {
|
2018-09-14 16:38:17 +00:00
|
|
|
const returnValue = splice.apply(this, args);
|
2018-09-14 15:57:26 +00:00
|
|
|
this._limit();
|
|
|
|
return returnValue;
|
|
|
|
};
|
2018-08-30 00:14:57 +00:00
|
|
|
|
2018-09-14 16:38:17 +00:00
|
|
|
// All mutable array methods build on top of insertAt
|
2018-09-14 15:57:26 +00:00
|
|
|
array.insertAt = function(...args) {
|
2018-09-14 16:38:17 +00:00
|
|
|
const returnValue = insertAt.apply(this, args);
|
2018-09-14 15:57:26 +00:00
|
|
|
this._limit();
|
|
|
|
this.arrayContentDidChange();
|
2018-08-30 00:14:57 +00:00
|
|
|
return returnValue;
|
|
|
|
};
|
|
|
|
|
|
|
|
array.unshift = function() {
|
|
|
|
throw new Error('Cannot unshift onto a RollingArray');
|
|
|
|
};
|
|
|
|
|
|
|
|
return array;
|
|
|
|
}
|