当前位置:首页 > JavaScript

js实现环形

2026-04-06 09:40:02JavaScript

实现环形数组的基本操作

环形数组(Circular Buffer)是一种固定大小的数据结构,遵循先进先出(FIFO)原则,当数组填满时,新数据会覆盖最旧的数据。以下是JavaScript实现环形数组的关键方法:

class CircularBuffer {
  constructor(capacity) {
    this.buffer = new Array(capacity);
    this.capacity = capacity;
    this.head = 0; // 写入指针
    this.tail = 0; // 读取指针
    this.size = 0; // 当前元素数量
  }

  // 添加元素到环形数组
  enqueue(item) {
    this.buffer[this.head] = item;
    this.head = (this.head + 1) % this.capacity;
    if (this.size === this.capacity) {
      this.tail = (this.tail + 1) % this.capacity;
    } else {
      this.size++;
    }
  }

  // 从环形数组移除元素
  dequeue() {
    if (this.size === 0) return undefined;
    const item = this.buffer[this.tail];
    this.tail = (this.tail + 1) % this.capacity;
    this.size--;
    return item;
  }

  // 查看下一个将被移除的元素
  peek() {
    return this.size === 0 ? undefined : this.buffer[this.tail];
  }

  // 清空环形数组
  clear() {
    this.head = 0;
    this.tail = 0;
    this.size = 0;
  }
}

环形数组的应用场景

环形数组特别适合以下场景:

  • 数据流处理(如音频/视频缓冲)
  • 固定大小的历史记录存储
  • 滑动窗口算法实现
  • 高性能队列需求(避免数组元素移动)

环形数组的变体实现

如果需要线程安全版本或支持动态扩容,可以扩展基础实现:

js实现环形

class DynamicCircularBuffer {
  constructor(initialCapacity = 8) {
    this.buffer = new Array(initialCapacity);
    this.capacity = initialCapacity;
    this.head = 0;
    this.tail = 0;
    this.size = 0;
  }

  // 动态扩容版本
  enqueue(item) {
    if (this.size === this.capacity) {
      this.resize(this.capacity * 2);
    }
    this.buffer[this.head] = item;
    this.head = (this.head + 1) % this.capacity;
    this.size++;
  }

  resize(newCapacity) {
    const newBuffer = new Array(newCapacity);
    for (let i = 0; i < this.size; i++) {
      newBuffer[i] = this.buffer[(this.tail + i) % this.capacity];
    }
    this.buffer = newBuffer;
    this.capacity = newCapacity;
    this.tail = 0;
    this.head = this.size;
  }
}

性能优化建议

  • 使用TypedArray(如Uint8Array)处理二进制数据
  • 批量操作时考虑缓存局部性
  • 对于高频操作场景,避免动态扩容
  • 使用位运算代替模运算(当容量为2的幂时)

标签: 环形js
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整数…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

js实现视口

js实现视口

js实现视口检测的方法 使用JavaScript检测元素是否进入视口(viewport)可以通过Intersection Observer API或手动计算元素位置实现。以下是两种常见方法: Int…