Is there some data-type like array that contains only last 100 elements? Or How to do this on my own?
We can just slice array from 0 to x element, when array length will be more than 100, but this is inefficient.
Is there some data-type like array that contains only last 100 elements? Or How to do this on my own?
We can just slice array from 0 to x element, when array length will be more than 100, but this is inefficient.
You could use a ring buffer:
var n = 100;
var a = new Array(n);
var i = 0;
function push(x) {
i = (i + 1) % n;
a[i] = x;
}
You could use push
and shift
:
var a = [];
function append(value) {
a.push(value);
while (a.length > 10) {
a.shift();
}
}
for (var i = 0; i < 75; i++) {
append(i);
}
console.log(a);
// Output:
// [ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 ]