Skip to content

Instantly share code, notes, and snippets.

@williammartin
Created June 16, 2022 09:39
Show Gist options
  • Save williammartin/6bd99acddb952043ea737f5837deda34 to your computer and use it in GitHub Desktop.
Save williammartin/6bd99acddb952043ea737f5837deda34 to your computer and use it in GitHub Desktop.
circular-buffer.ts
export default class CircularBuffer<T> {
readonly #capacity: number
readonly #values: T[]
#size: number
#head: number
#tail: number
constructor(capacity: number) {
this.#capacity = capacity
this.#values = []
this.#size = 0
this.#head = 0
this.#tail = 0
}
write(value: T) {
if (this.isFull()) {
throw new BufferFullError()
}
this.#values[this.#tail] = value
this.#size++
this.#tail++
if (this.shouldTailWrap()) {
this.#tail = 0
}
}
read(): T {
if (this.isEmpty()) {
throw new BufferEmptyError()
}
const v = this.#values[this.#head]
this.#size--
this.#head++
if (this.shouldHeadWrap()) {
this.#head = 0
}
return v
}
forceWrite(value: T) {
if (!this.isFull()) {
this.write(value)
return
}
this.#values[this.#tail] = value
this.#head++
this.#tail++
if (this.shouldHeadWrap()) {
this.#head = 0
}
if (this.shouldTailWrap()) {
this.#tail = 0
}
}
clear() {
this.#size = 0
this.#head = 0
this.#tail = 0
}
private shouldHeadWrap(): boolean {
return this.#head == this.#capacity
}
private shouldTailWrap(): boolean {
return this.#tail == this.#capacity
}
private isEmpty(): boolean {
return this.#size == 0
}
private isFull(): boolean {
return this.#size == this.#capacity
}
}
export class BufferFullError extends Error {
constructor() {
super()
}
}
export class BufferEmptyError extends Error {
constructor() {
super()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment