Javascript

环形数组 js

本文主要是介绍环形数组 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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!