@thi.ng/buffers
Version:
General purpose and generic read/write buffer implementations with different behaviors/orderings
41 lines (40 loc) • 719 B
JavaScript
import { assert } from "@thi.ng/errors/assert";
const lifo = (cap) => new LIFOBuffer(cap);
class LIFOBuffer {
constructor(cap = 1) {
this.cap = cap;
assert(cap >= 1, `capacity must be >= 1`);
}
buf = [];
get length() {
return this.buf.length;
}
clear() {
this.buf.length = 0;
}
copy() {
const buf = new LIFOBuffer(this.buf.length);
buf.buf = this.buf.slice();
return buf;
}
readable() {
return this.buf.length > 0;
}
read() {
return this.buf.pop();
}
peek() {
return this.buf[this.buf.length - 1];
}
writable() {
return this.buf.length < this.cap;
}
write(x) {
this.buf.push(x);
return true;
}
}
export {
LIFOBuffer,
lifo
};