Sha256: 5d53443984402019a282e708ea51b8fb35c3054783477e58b1d530968c800709

Contents?: true

Size: 946 Bytes

Versions: 131

Compression:

Stored size: 946 Bytes

Contents

interface Buffer<T> {
  read(): T | undefined
  write(value: T): void
  clear(): void
}

export class BufferOverflowError extends Error {
  constructor() {
    super("Buffer is full.")
  }
}

export class BufferEmptyError extends Error {
  constructor() {
    super("Buffer is empty.")
  }
}

export default class CircularBuffer<T> implements Buffer<T> {
  private capacity: number
  private buffer: T[] = []

  constructor(capacity: number) {
    this.capacity = capacity
  }

  public read() {
    if (this.buffer.length === 0) {
      throw new BufferEmptyError()
    }
    return this.buffer.shift()
  }

  public write(value: T) {
    if (this.buffer.length + 1 > this.capacity) {
      throw new BufferOverflowError()
    }
    this.buffer.push(value)
  }

  public forceWrite(value: T) {
    if (this.buffer.length === this.capacity) {
      this.read()
    }
    this.buffer.push(value)
  }

  public clear() {
    this.buffer = []
  }
}

Version data entries

131 entries across 131 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.179 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.178 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.177 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.176 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.175 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.174 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.173 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.172 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.171 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.170 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.169 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.167 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.166 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.165 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.164 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.163 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.162 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.161 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.160 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts