github.com/hernad/nomad@v1.6.112/ui/app/utils/classes/rolling-array.js (about)

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