fastds
Version:
Fast, Zero-Dependency, TypeScript-based data structures for high-performance applications.
111 lines (109 loc) • 3.08 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "BinarySearchArray", {
enumerable: true,
get: function() {
return BinarySearchArray;
}
});
const _ringbuffercjs = require("./ring-buffer.cjs");
class BinarySearchArray {
#buffer;
#comparator;
constructor(comparator){
this.#buffer = new _ringbuffercjs.RingBuffer();
this.#comparator = comparator;
}
[Symbol.toStringTag] = 'BinarySearchArray';
get length() {
return this.#buffer.length;
}
at(index) {
return this.#buffer.peekAt(index);
}
lowerBound(value) {
const length = this.#buffer.length;
if (length === 0) return 0;
const buffer = this.#buffer;
const comparator = this.#comparator;
let left = 0;
let right = length;
while(left < right){
const mid = left + right >>> 1;
const midValue = buffer.peekAt(mid);
if (comparator(midValue, value) < 0) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
upperBound(value) {
const length = this.#buffer.length;
if (length === 0) return 0;
const buffer = this.#buffer;
const comparator = this.#comparator;
let left = 0;
let right = length;
while(left < right){
const mid = left + right >>> 1;
const midValue = buffer.peekAt(mid);
if (comparator(midValue, value) <= 0) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
indexOf(value, index = 0) {
const length = this.#buffer.length;
if (length === 0 || index >= length) return -1;
const buffer = this.#buffer;
const comparator = this.#comparator;
let left = index;
let right = length - 1;
while(left <= right){
const mid = left + right >>> 1;
const midValue = buffer.peekAt(mid);
const cmp = comparator(midValue, value);
if (cmp === 0) {
return mid;
} else if (cmp < 0) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
has(value) {
return this.indexOf(value) !== -1;
}
insert(value) {
const index = this.lowerBound(value);
this.#buffer.setOne(index, value, true);
return index;
}
removeOne(index) {
return this.#buffer.removeOne(index);
}
removeFirst(value) {
const index = this.indexOf(value);
return this.#buffer.removeOne(index);
}
remove(index, count) {
this.#buffer.deallocate(index, count);
return this;
}
iter() {
return this.#buffer.iter();
}
[Symbol.iterator]() {
return this.#buffer[Symbol.iterator]();
}
}
//# sourceMappingURL=binary-search.cjs.map