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._array.pop();
}
}
HangoutStack.prototype.getAllItems = function()
{
return this._array;
}
Sounds like it would be a lot easier to use an array. Then you could use
unshiftto insert from the beginning andpopto remove from the end.Edit: Example:
Alternatively, you could use
push/shiftinstead ofunshift/pop. Depends on which end of the array you prefer the new items to sit at.