示例工程 23-project-stream-workbench

23-project-stream-workbench/demo-01-ring-buffer/ring.ts

typescript · 1.6 KB

type LogEvent = { id: number; source: string };

class RingBuffer<T> {
  private items: T[] = [];
  private total = 0;
  private droppedCount = 0;

  constructor(private readonly capacity: number) {
    if (!Number.isInteger(capacity) || capacity <= 0) {
      throw new RangeError("BAD_CAPACITY");
    }
  }

  get received(): number {
    return this.total;
  }

  get stored(): number {
    return this.items.length;
  }

  get dropped(): number {
    return this.droppedCount;
  }

  pushMany(batch: T[]): number {
    this.total += batch.length;
    this.items.push(...batch);
    const overflow = Math.max(0, this.items.length - this.capacity);
    if (overflow > 0) {
      this.items = this.items.slice(overflow);
      this.droppedCount += overflow;
    }
    return overflow;
  }

  toArray(): T[] {
    return [...this.items];
  }
}

const buffer = new RingBuffer<LogEvent>(5);
buffer.pushMany([
  { id: 1, source: "build" },
  { id: 2, source: "network" },
  { id: 3, source: "tools" },
]);
const firstOverflow = buffer.pushMany([
  { id: 4, source: "build" },
  { id: 5, source: "network" },
  { id: 6, source: "tools" },
  { id: 7, source: "build" },
]);
const ids = buffer.toArray().map((event) => event.id);

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      firstOverflow === 2 &&
      buffer.received === 7 &&
      buffer.stored === 5 &&
      buffer.dropped === 2 &&
      buffer.received === buffer.stored + buffer.dropped &&
      ids.join(",") === "3,4,5,6,7",
    firstOverflow,
    received: buffer.received,
    stored: buffer.stored,
    dropped: buffer.dropped,
    ids,
  }),
);