limit-queue.ts 532 B

123456789101112131415161718192021222324
  1. /**
  2. * Limit Queue
  3. * The first element will be removed when the length exceeds the limit
  4. */
  5. export class LimitQueue<T> extends Array<T> {
  6. __limit;
  7. __onExceed? : (item : T | undefined) => void;
  8. constructor(limit: number) {
  9. super();
  10. this.__limit = limit;
  11. }
  12. pushItem(value : T) {
  13. super.push(value);
  14. if (this.length > this.__limit) {
  15. const item = this.shift();
  16. if (this.__onExceed) {
  17. this.__onExceed(item);
  18. }
  19. }
  20. }
  21. }