Sha256: b135e0a4c02b20d4045806c733a37449cb0c7cf84030a700fd3a774afc3b2507

Contents?: true

Size: 895 Bytes

Versions: 185

Compression:

Stored size: 895 Bytes

Contents

let buffer,
  bufferMax;

export class BufferEmptyError extends Error {
  constructor(message) {
    super();
    this.message = message || 'Buffer is empty.';
  }
}
export class BufferFullError extends Error {
  constructor(message) {
    super();
    this.message = message || 'Buffer is full.';
  }
}

const read = () => {
  if (buffer.length === 0) {
    throw new BufferEmptyError();
  }
  return buffer.splice(0, 1)[0];
};

const write = (value) => {
  if (buffer.length === bufferMax) {
    throw new BufferFullError();
  }
  value ? buffer.push(value) : null;
};

const forceWrite = (value) => {
  if (buffer.length === bufferMax) {
    read();
  }
  write(value);
};

const clear = () => buffer = [];

const CircularBuffer = (capacity) => {
  buffer = [];
  bufferMax = capacity;
  return {
    read,
    write,
    forceWrite,
    clear,
  };
};

export { CircularBuffer as default };

Version data entries

185 entries across 185 versions & 1 rubygems

Version Path
trackler-2.2.0.5 tracks/ecmascript/exercises/circular-buffer/example.js
trackler-2.2.0.4 tracks/ecmascript/exercises/circular-buffer/example.js
trackler-2.2.0.3 tracks/ecmascript/exercises/circular-buffer/example.js
trackler-2.2.0.2 tracks/ecmascript/exercises/circular-buffer/example.js
trackler-2.2.0.1 tracks/ecmascript/exercises/circular-buffer/example.js