buddy

node MVC discord bot
Log | Files | Refs | README

LimitedCollection.js (885B)


      1 'use strict';
      2 
      3 const Collection = require('./Collection.js');
      4 
      5 /**
      6  * A Collection which holds a max amount of entries. The first key is deleted if the Collection has
      7  * reached max size.
      8  * @extends {Collection}
      9  * @param {number} [maxSize=0] The maximum size of the Collection
     10  * @param {Iterable} [iterable=null] Optional entries passed to the Map constructor.
     11  * @private
     12  */
     13 class LimitedCollection extends Collection {
     14   constructor(maxSize = 0, iterable = null) {
     15     super(iterable);
     16     /**
     17      * The max size of the Collection.
     18      * @type {number}
     19      */
     20     this.maxSize = maxSize;
     21   }
     22 
     23   set(key, value) {
     24     if (this.maxSize === 0) return this;
     25     if (this.size >= this.maxSize && !this.has(key)) this.delete(this.firstKey());
     26     return super.set(key, value);
     27   }
     28 
     29   static get [Symbol.species]() {
     30     return Collection;
     31   }
     32 }
     33 
     34 module.exports = LimitedCollection;