环形数组 js

export default class AnnularArray {
  #arr = null
  #len = 0
  #offset = 0
  #final = 0
  constructor(len) {
    this.#arr = new Array(len)
    this.#len = len
  }

  get size() {
    return (this.#final + this.#len - this.#offset) % this.#len
  }

  push(val) {
    if ((this.#final + this.#len + 1) % this.#len === this.#offset)
      throw new Error(‘存入失败, 内存溢出了~‘)
    this.#arr[this.#final] = val
    this.#final = (this.#final + 1) % this.#len
  }

  fetch() {
    if (this.#final === this.#offset) throw new Error(‘取出失败, 没有数据了~‘)
    const num = this.#arr[this.#offset]
    this.#offset = (this.#offset + 1) % this.#len
    return num
  }

  each(callBack) {
    for (let i = this.#offset; i < this.#offset + this.size; i++) {
      const item = this.#arr[i % this.#len]
      callBack ? callBack(item) : console.log(item)
    }
  }
}

环形数组 js

上一篇:算法题解----leetcode.826.安排工作以达到最大收益


下一篇:python-对指定字符串排列组合并去重