gristlabs_grist-core/app/common/CircularArray.js
Jarosław Sadziński a52d56f613 (core) Moving client and common tests to core
Summary:
- Moved /test/client and /test/common to core.
- Moved two files (CircularArray and RecentItems) from app/common to core/app/common.
- Moved resetOrg test to gen-server.
- `testrun.sh` is now invoking common and client test from core.
- Added missing packages to core's package.json (and revealed underscore as it is used in the main app).
- Removed Coord.js as it is not used anywhere.

Test Plan: Existing tests

Reviewers: paulfitz

Reviewed By: paulfitz

Subscribers: paulfitz

Differential Revision: https://phab.getgrist.com/D3590
2022-08-23 19:20:10 +02:00

45 lines
1.2 KiB
JavaScript

/**
* Array-like data structure that lets you push elements to it, but holds only the last N of them.
*/
function CircularArray(maxLength) {
this.maxLength = maxLength;
this._data = [];
this._offset = 0;
}
/**
* @property {Number} - the number of items in the CircularArray.
*/
Object.defineProperty(CircularArray.prototype, "length", {
get: function() { return this._data.length; }
});
/**
* @param {Number} index - An index to fetch, between 0 and length - 1.
* @returns {Object} The item at the given index.
*/
CircularArray.prototype.get = function(index) {
return this._data[(this._offset + index) % this.maxLength];
};
/**
* @param {Object} item - An item to push onto the end of the CircularArray.
*/
CircularArray.prototype.push = function(item) {
if (this._data.length < this.maxLength) {
this._data.push(item);
} else {
this._data[this._offset] = item;
this._offset = (this._offset + 1) % this.maxLength;
}
};
/**
* Returns the entire content of CircularArray as a plain array.
*/
CircularArray.prototype.getArray = function() {
return this._data.slice(this._offset).concat(this._data.slice(0, this._offset));
};
module.exports = CircularArray;