I want to create a helper object that will work the following way:
It is an array with a given number of rows, for example let’s say it can hold only 3 rows.
It will have an insert method that inserts the a new entry at the first index, and pushes one index down all the rest (new entry is 0, 0 becomes 1, 1–>2 etc..)
and if the array is full to the max number of rows, the last entry drops out.
So I made it the following way:
function limArray(array, maxlength){
this.arr = array;
this.maxlength = maxlength;
this.arr.length = maxlength;
this.insertVal = function(value){ //insert new value and push down the rest
for (var i=maxlength; i>=0; i--) {
this.arr[i] = this.arr[i-1]
};
this.arr[0] = value;
this.arr.length = maxlength;
};
}
My question is, if it’s a smart way to make this?
Is it possible to create instance of the Array object itself and modify it to be limited etc..
Any critique / improvement suggestions are welcome!
You could overwrite the
pushmethod:As @alnorth29 mentioned, you can use
unshiftto prepend a value. You can overwrite this as well:Of course you can also attach a new property with a more expressive name than
unshift:If you extend an array instance like this, make sure you only traverse over its elements with a
forloop, not with afor...inloop (you should always useforfor arrays anyway). Another possibility is to define the property using ECMAScript 5’sObject.defineProperty[docs] and setenumerabletofalse. But it is only supported in newer browsers.There are other ways to add elements to an array, but I assume you are not going to use them .
Usage:
Update:
I forgot, in case the array passed to the function already exceeds the maximum number of elements, you have to reduce the length: