circular-buffer.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. export class BufferFullError extends Error {
  2. }
  3. export class BufferEmptyError extends Error {
  4. }
  5. export default class CircularBuffer<T> {
  6. protected base: number;
  7. protected cap: number;
  8. protected data: Array<T>
  9. protected len: number;
  10. constructor(initial: number) {
  11. if (initial % 1 !== 0) {
  12. throw new Error("initial capacity must be an integer");
  13. }
  14. this.base = 0;
  15. this.cap = initial;
  16. this.data = new Array<T>(this.cap)
  17. this.len = 0;
  18. }
  19. write(value: T): void {
  20. if (this.len === this.cap) {
  21. throw new BufferFullError();
  22. }
  23. this.data[(this.base + this.len) % this.cap] = value;
  24. this.len++;
  25. }
  26. read(): T {
  27. if (this.len === 0) {
  28. throw new BufferEmptyError();
  29. }
  30. const value = this.data[this.base];
  31. this.base = (this.base + 1) % this.cap;
  32. this.len--;
  33. return value;
  34. }
  35. forceWrite(value: T): void {
  36. this.data[(this.base + this.len) % this.cap] = value;
  37. if (this.cap === this.len) {
  38. this.base = (this.base + 1) % this.cap;
  39. return;
  40. }
  41. this.len++;
  42. }
  43. clear(): void {
  44. this.base = 0;
  45. this.data = new Array<T>(this.cap)
  46. this.len = 0;
  47. }
  48. }