Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:

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)

share|improve this question

1 Answer 1

up vote 2 down vote accepted

There is no native way to do this so your general logic seems sound. Here's some improvements, you might consider:

  1. 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.

  2. Ensure the array stays below max length even if it was previously above max

  3. 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] + "<br>");
}


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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.