Is there a standard method to have special Array which can store last N elements (probably with an internal index to keep current item) such that when it reaches to and pass the last index, it goes to beginning and over-write the most old items. This way we have always the last recent N items. This is useful for example to store recent 10 price values of a product.
I can write a custom function may be like as below but i guess there may be some built-in method for it as it has many uses.
var n = 10; //max number of elements var a = new Array(n); //init the array var i = 0; //current position function setNext(value) { i++; if(i >= n) i=0; a[i] = value; } function getLast() { return a[i]; } function getAll() { //return concat(a[i+1...n], a[0...i]); //all items from old to new ones } Sample data:
// consider n = 10 // assume we set 10 numbers in array, setNext(101); setNext(102); //now a is: a = [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]; // cur index: 9 //now, if we add another value like as 111, it should take // position of oldest item of list which is currently 101: a = [ *111*, 102, 103, 104, 105, 106, 107, 108, 109, 110]; //cur index: 1