Skip to content

Instantly share code, notes, and snippets.

@yonixw
Created December 13, 2023 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yonixw/e1ef46c066ce70f51a0b9fca4aa5a593 to your computer and use it in GitHub Desktop.
Save yonixw/e1ef46c066ce70f51a0b9fca4aa5a593 to your computer and use it in GitHub Desktop.
JS Circular Buffer
function make_CRS_Buffer(size) {
//based on https://stackoverflow.com/a/60285222/1997873
return {
arr: [],
arr_i: 0,
arr_size: size,
size: function () {
return this.arr.length;
},
full: function () {
return this.arr.length == this.arr_size;
},
clear: function () {
this.A = [];
},
add: function (value) {
this.arr[this.arr_i] = value;
this.arr_i = (this.arr_i + 1) % this.arr_size;
},
get: function (i) {
var mAi = this.arr.length < this.arr_size ? 0 : this.arr_i;
return this.arr[(mAi + i) % this.arr_size];
},
forall: function (callback) {
var mAi = this.arr.length < this.arr_size ? 0 : this.arr_i;
for (var i = 0; i < this.arr.length; i++) {
callback(this.arr[(mAi + i) % this.arr_size]);
}
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment