ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

环形数组 js

2021-08-26 02:00:05  阅读:41  来源: 互联网

标签:arr .# 环形 len js item 数组 offset final


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)
    }
  }
}

标签:arr,.#,环形,len,js,item,数组,offset,final
来源: https://www.cnblogs.com/snowowl/p/15187701.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有