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.139 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.138 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.137 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.136 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.135 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.134 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.133 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.132 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.131 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.130 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.129 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.128 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.127 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.126 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.125 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.124 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.123 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.122 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.121 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts
trackler-2.2.1.120 tracks/typescript/exercises/circular-buffer/circular-buffer.example.ts