环形数组 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)
    }
  }
}

上一篇:FLINK实例(134):自定义时间和窗口的操作符(15)Flink 时间窗口的起始时间


下一篇:一、Redis命令使用