JavaScript object properties count limit, deleting oldest updated ones
The only reliable way to determine "oldest" is to keep some kind of index, probably using an array. Whenever you update the object, you check if the property exists or not using propertyName in Object
. If it does, splice it from the array and use unshift to put it at index 0, then update its value on the object.
If it doesn't exist already, and the array length is equal to max property count, pop
the oldest property name off the array, unshift
the new property to index 0, delete
the old property from the object and add the new property.
If it doesn't exist and the array length is less than the max property count, unshift
the name on the array to add it at index 0 and add it to the object.
Edit
Some code. Note that you need to protect against overwriting the *_maxPropCount* and *_index* properties, I'll leave that to you.
var o = {a:1, b:2, _maxPropCount: 2, _index: ['a','b']};function updateObject(obj, prop, value) { var idx = obj._index; var i, lastProp; // If property exists, move to start of index array if (prop in obj) { i = idx.indexOf(prop); idx.unshift(idx.splice(i, 1)); // Otherwise, property doesn't exist so check length and // number of properties } else { // If already have full count, pop last property name from end of array // and delete from object if (idx.length == o._maxPropCount) { lastProp = idx.pop(); delete o[lastProp]; } // Update index idx.unshift(prop); } // Update object obj[prop] = value;}updateObject(o, 'b', 6);alert(o._index + ' ' + o.b); // b,a 6updateObject(o, 'g', 2);alert(o._index + ' ' + o.a); // g,b undefined
The code could be shorter by a few lines, but that won't make it any faster. Oh, and indexOf is ES5 so not available on older browsers, a shim is required which will be slow for UAs that need to use it if you have many properties.
If you are in node.js, you can take advantage of a surprising feature of object properties: they are returned in the order in which they were added. So you can just define an object with a few properties:
var array = { fake1: 'fake', fake2: 'fake' };
And then every time you add a new property, you remove the first one:
for (var i in array) { delete array[i]; break;}
When you update a property, you have to remove it and then re-add it so it goes at the end again.
It is simple yet very effective: you will always have the newest two properties in your object. You don't need to keep extra data or go over the set of properties each time you operate on an element.
I have not tested this with in-browser JavaScript engines; you should not rely on order of properties because the language makes no guarantees, but apparently it works too.