Created
December 13, 2023 12:25
-
-
Save yonixw/e1ef46c066ce70f51a0b9fca4aa5a593 to your computer and use it in GitHub Desktop.
JS Circular Buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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