{"size": 1154, "ext": "js", "max_stars_repo_path": "src/sliding_buffer.js", "max_stars_repo_name": "corporealfunk/pvocjs", "max_stars_repo_stars_event_min_datetime": "2021-05-03T01:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T01:56:43.000Z", "max_issues_repo_path": "src/sliding_buffer.js", "max_issues_repo_name": "corporealfunk/pvocjs", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sliding_buffer.js", "max_forks_repo_name": "corporealfunk/pvocjs", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.6274509804, "max_line_length": 73, "alphanum_fraction": 0.650779896}
import { zeroArray } from './utilties';

class SlidingBuffer {
  constructor(size) {
    this.size = size;

    this.buffer = Array(size);
    zeroArray(this.buffer);

    this.lastValidDataI = size;
  }

  get hasValidData() {
    return (this.lastValidDataI >= 0 && this.lastValidDataI < this.size);
  }

  // returns to you the data that got shifted out
  shiftIn(data, validData = true) {
    if (data.length > this.size) {
      throw new Error('Cannot shiftIn more data than buffer size');
    }

    const shiftedOut = this.buffer.slice(0, data.length);

    this.buffer = this.buffer.slice(data.length, this.buffer.length);
    this.buffer.push(...data);

    if (validData) {
      this.lastValidDataI = this.size - 1;
    }

    return shiftedOut;
  }

  // shifts the contents to the left by length and pads with 0
  // returns to you the shiftedOut data
  shiftLeft(length) {
    if (length > this.size) {
      throw new Error('Cannot shiftOver more than buffer size');
    }

    const data = Array(length);
    zeroArray(data);

    this.lastValidDataI -= length;
    return this.shiftIn(data, false);
  }
}

export default SlidingBuffer;
