patternjavascriptMinor
Maximum number of values in an array
Viewed 0 times
valuesnumbermaximumarray
Problem
I have an array to have a maximum of 10 elements. Whenever I add a new element, if it already has 10, it would remove the first and push a new one.
I made this:
Which seems to work fine, however, I'm just wondering if there is a better way to do it (perhaps some native JavaScript function)
I made this:
Array.prototype.pushMax = function(value,max){
if (this.length >= max){
this.shift();
}
this.push(value);
}Which seems to work fine, however, I'm just wondering if there is a better way to do it (perhaps some native JavaScript function)
Solution
There is no native way to do this so your general logic seems sound. Here's some improvements, you might consider:
-
Make sure the pushMax function is not enumerable so people who iterate arrays with
-
Ensure the array stays below max length even if it was previously above max
-
Return the new length of the array, the same as
Here's a working snippet:
You could also consider making the max length be a non-enumerable property of the array so you don't have to pass it to
I'd really rather see this in a subclass of an Array rather than modifying the built-in Array object, but alas we can't subclass the Array object yet in most browsers.
-
Make sure the pushMax function is not enumerable so people who iterate arrays with
for (var index in array) won't see the pushMax property.-
Ensure the array stays below max length even if it was previously above max
-
Return the new length of the array, the same as
.push():Here's a working snippet:
Object.defineProperty(Array.prototype, "pushMax", {
configurable: false,
enumerable: false,
writable: false,
value: function(value, max) {
if (this.length >= max) {
this.splice(0, this.length - max + 1);
}
return this.push(value);
}
});
var x = [0,1,2,3,4,5,6,7,8,9,10];
x.pushMax(11, 10);
x.pushMax(12, 10);
x.pushMax(13, 10);
// wrong way to iterate an array, but just testing enumerability
for (var i in x) {
document.write(i + ": " + x[i] + "
");
}
You could also consider making the max length be a non-enumerable property of the array so you don't have to pass it to
.pushMax() every time.I'd really rather see this in a subclass of an Array rather than modifying the built-in Array object, but alas we can't subclass the Array object yet in most browsers.
Context
StackExchange Code Review Q#101235, answer score: 3
Revisions (0)
No revisions yet.