JavaScript 中的循环缓冲区
有人已经在 JavaScript 中实现了循环缓冲区吗?如果没有指针,您将如何做到这一点?
Has anyone already implemented a circular buffer in JavaScript? How would you do that without having pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(22)
奇怪的巧合,我今天早些时候刚刚写了一篇!我不知道您的具体要求是什么,但这可能有用。
它提供了一个类似于无限长度数组的界面,但“忘记”了旧项目:
Strange co-incidence, I just wrote one earlier today! I don't know what exactly your requirements are but this might be of use.
It presents an interface like an Array of unlimited length, but ‘forgets’ old items:
更新:如果您仅用数字填充缓冲区,这里有一些单行插件:
Update: in case you fill the buffer with numbers only, here are some one liner plugins:
和其他许多人一样,我喜欢 noiv 的解决方案,但我想要一个更好的 API:
对原始版本的改进:
get< /code> 支持默认参数(返回推送到缓冲区的最后一项)
get
支持负索引(从右开始计数)prev
将缓冲区向后移动一个并返回其中的内容(例如弹出而无需删除)next
撤消上一个(向前移动缓冲区并返回它)我用它来存储命令历史记录,然后我可以使用其
prev
和在应用程序中翻阅该命令历史记录>next
方法,当它们无处可去时,它们很好地返回未定义。Like many others, I liked noiv's solution, but I wanted a somewhat nicer API:
Improvements over original:
get
supports default argument (returns last item pushed onto buffer)get
supports negative indexing (counts from right)prev
moves buffer back one and returns what's there (like popping without delete)next
undoes prev (moves buffer forward and returns it)I used this to store a command history which I could then flip through in an app using its
prev
andnext
methods, which nicely return undefined when they have nowhere to go.差不多 10 年后,一个使用 JavaScript ES6 的答案:
Almost 10 years later, an answer using JavaScript ES6:
这是您可以使用的代码的快速模型(它可能不起作用并且存在错误,但它显示了它可以完成的方式):
使用这个对象就像:
您当然可以使用数组来实现它以及一个在内部使用数组并保留当前项目索引值并移动该索引的类。
This is a quick mockup of the code you could use (it probably isn't working and has bugs in it, but it shows the way it could be done):
using this object would be like:
You could of course implement it using array as well with a class that would internally use an array and keep a value of the current item index and moving that one.
我个人使用 Trevor Norris 的实现,您可以在这里找到:
https://github.com/trevnorris/cbuffer
我对此非常满意:-)
I use personally the implementation of Trevor Norris that you can find here:
https://github.com/trevnorris/cbuffer
and I'm quite happy with it :-)
简短而甜蜜:
输出:
Short and sweet:
Output:
这是我的看法。具体来说,这是一个非常简单的圆形/环形滑动缓冲区的对象实现。
一点旁注。尽管人们称其为相似的名称,“圆形”、“环”、“队列”,但还是值得澄清,因为它们可能意味着不同的东西。
环形/循环队列。您可以将元素添加到头部,然后从末尾裁剪它们。最小大小为 0,最大大小是底层数组的大小。队列环绕底层数组。
同样的东西,队列,先进先出,先进先出,但具有可变(不确定)最大大小,并使用标准 push() 和 unshift() 数组方法实现。要添加元素,您只需将其推送()到数组中,并使用 unshift() 它即可使用元素,就是这样,相当标准的函数,无需发明任何东西。
大小恒定的滑动缓冲区,新元素添加到头部(右),缓冲区向后滑动(左),最左边多余的元素会自动丢失。从概念上讲,它是一个滑动缓冲区,它恰好作为循环/环形缓冲区实现最有效。
这是第(3)种的实现。这可以用作并且主要用作数据可视化小部件的后端,例如用于实时监控的滑动线图。
对象:
用法:
并且,一个完整的功能示例,两个缓冲区并行运行:
希望它会有用。
Here's my take. Specifically this is a very simple object implementation of a circular/ring sliding buffer.
A little side note. Despite the fact that people call it similar names, "circular", "ring", "queue", it should be worth clarifying, because they can mean different things.
A ring/circular queue. You can add elements to the head, and crop them from the end. Min size is 0, max size is the size of underlying array. The queue wraps around the underlying array.
The same thing, a queue, FIFO, first-in-first-out, but with variable (indefinite) max size, and implemented using standard push() and unshift() array methods. To add element, you simply push() it onto an array, and to consume element you unshift() it, that's it, pretty standard functions, no need to invent anything.
A sliding buffer of constant size, where new elements are added to the head (right), the buffer slides back (left), and left-most excessive elements are automatically lost. Conceptually it is a sliding buffer, it just happens to get implemented most efficiently as a circular/ring one.
This is the implementation of a (3) kind. This can be used, and is primarily intended, as a back-end of a data visualization widget, e.g. a sliding line graph for real-time monitoring.
The object:
Usage:
And, a complete functional example, with two buffers running in parallel:
Hope it'll be useful.
我们可以不用JavaScript来实现循环队列,而是使用数组的一些内置函数来实现循环队列。
例子:
假设我们需要实现长度为4的循环队列。
输出:
circular
[4, 3, 2, 1]
如果您尝试向此数组添加另一个元素,例如:
输出:
circular
[5,4,3,2]
Instead of implementing circular queue with JavaScript, we can use some inbuilt functions of array to achieve circular queue implementation.
example:
Suppose we need to implement the circular queue for length 4.
Output:
circular
[4, 3, 2, 1]
If you try to add another element to this array eg:
Output:
circular
[5, 4, 3, 2]
很多答案,但没有看到类似以下功能简单方法的东西...类似(ES6)的东西:
这可以用作减速器。例如,在
scan
中的可观察流中。编辑
并不是我现在看到的这个特定问题的真正答案,因为它不提供阅读位置...:)
A lot of answers, but didn't see something like the following functional simple approach... Something like (ES6):
This can be used as a reducer. E.g. in observable streams in
scan
.edit
Not really an answer to this particular question I see now, cause it doesn't provide a read position... :)
我无法让 Robert Koritnik 的代码工作,所以我将其编辑为以下似乎有效的内容:
使用:
I couldn't get Robert Koritnik's code to work, so I edited it to the following which seems to work:
To use:
我建议使用 TypeScript 循环数组实现: https://gist.github.com/jerome-benoit /c251bdf872473d1f86ea3a8b90063c90。
它很精简,API 与标准数组对象相同。
I recommend using that TypeScript circular array implementation: https://gist.github.com/jerome-benoit/c251bdf872473d1f86ea3a8b90063c90.
It is lean and the API is the same as the standard array object.
一种方法是像其他人建议的那样使用链表。另一种技术是使用一个简单的数组作为缓冲区,并通过该数组的索引来跟踪读取和写入位置。
One approach would be to use a linked list as others have suggested. Another technique would be to use a simple array as the buffer and to keep track of the read and write positions via indices into that array.
我认为你应该能够通过使用对象来做到这一点。像这样的事情:
现在您只需将值存储在每个链接的 value 属性中。
I think you should be able to do this by just using objects. Something like this:
Now you'd just store the value in each link's value property.
我真的很喜欢 noiv11 解决这个问题,并且根据我的需要,我添加了一个额外的属性“buffer”来返回缓冲区:
I really like how noiv11 solved this and for my need I added an extra property 'buffer' which returns the buffer:
感谢 noiv 提供的简单高效的解决方案。我还需要能够像 PerS 所做的 一样访问缓冲区,但我想按顺序获取项目额外。所以这就是我最终得到的结果:
这是测试套件:
Thanks noiv for your simple and efficient solution. I also needed to be able to access the buffer like PerS did, but i wanted to get the items in the order they were added. So here's what i ended up with:
Here is the test suite:
如果您现在 Array.prototype.length 是什么,那就非常简单了:
Its very easy if you now what Array.prototype.length is:
我更喜欢更简单的方法。在我看来,这应该是三行。
像这样
你就可以
I prefer simpler approaches. This should be a three-liner, IMO.
Something like
Then you can just
我没有进行任何性能检查,但根据我的理解,顺序数组访问应该比链表更快。我还注意到,多个实现都受到过时的基于 ES3(至少)原型的风格的困扰,这让我大吃一惊。而且它们都不支持动态大小增加,即“增长”。这就是我对这个实现的看法。请随意根据您的需要进行扩展:
为了防止在界面中传播
undefined
我可以建议以下版本:I wasn't doing any perf checks, but as per my understanding sequential array access should be faster than linked list. Also I've noticed that multiple implementations suffer from obsolete prototype based ES3 (at least) style which makes my eyeballs pop. Also none of them support dynamic size increase i.e. "growing". So here's how I see this implementation. Feel free to expand as per your needs:
To prevent propagation of
undefined
in the interface I can suggest the following version:我已经通过 OpenAI 将我的 python 库移植到 JavaScript,它有点像 python 风格,但功能强大(支持
.slice
、.extend
、真正的.pop
,以及 python 风格.remove(value)
。使用.append
而不是.push
)I have ported my python library to JavaScript via OpenAI, it's somewhat python-esque, but is highly functional (supports
.slice
,.extend
, a genuine.pop
, as well as python style.remove(value)
. Use.append
instead of.push
)使用 ES6 类,您可以创建如下结构:
Using ES6 classes you can do a structure like this: