开发者

Data-structure to store "last 10" data sets?

开发者 https://www.devze.com 2023-04-07 14:19 出处:网络
I\'m currently working with an object Literal to store temporary information to send to clients, it\'s like a history container for the last 10 sets of data.

I'm currently working with an object Literal to store temporary information to send to clients, it's like a history container for the last 10 sets of data.

So the issue that I', having is figuring out the most efficient way to splice on object as well as push an object in at the start, so basically i have an object, this object has 0 data inside of it.

I then insert values, but what I need to do is when the object reaches 10 keys, I need to pop the last element of the end of object literal, push all keys up and then insert one value at the start.

Take this example object

var initializeData = {
    a : {},
    b : {},
    c : {},
    d : {},
    e : {},
    f : {},
    g : {},
    h : {},
    i : {},
    j : {}
}

When I insert an element I need j to be removed, i to become the last element, and a to become b.

So that the new element becomes a.

Can anyone help me solve this issue, I am using node.js but native JavaScript is fine obviously.


Working with arrays after advice from replies, this is basically what I am thinking your telling me would be the best solution:

function HangoutStack(n)
{
    this._array = new Array(n);
    this.max    = n;
}

HangoutStack.prototype.push = function(hangout)
{
    if(this._array.unshift(hangout) > this.max)
    {
        this._arr开发者_如何学Pythonay.pop();
    }
}

HangoutStack.prototype.getAllItems = function()
{
    return this._array;
}


Sounds like it would be a lot easier to use an array. Then you could use unshift to insert from the beginning and pop to remove from the end.

Edit: Example:

var items = []

function addItem(item) {
  items.unshift(item)
  if (items.length > 10) {
    items.pop()
  }
}

Alternatively, you could use push/shift instead of unshift/pop. Depends on which end of the array you prefer the new items to sit at.


What you need is called a Circular Buffer. Have a look at this implementation in javascript


Yeah, use an Array.

var arr = [];

// adding an item
if (arr.unshift(item) > 10) {
    arr.pop();
}

If you need the 'name' of the item, like "a" or "b" in your object example, just wrap each item in another object that contains the name and the object.

Objects in js are like dictionaries -- they have no inherent order to the items. It's just a collection of things. You can try to make up an order (like a through z in your example), but then you have to manage that order yourself when things change. It's just much easier to use an array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号