@btc-vision/transaction
Version:
OPNet transaction library allows you to create and sign transactions for the OPNet network.
103 lines • 2.85 kB
JavaScript
import { FastMap } from './FastMap.js';
export class DeterministicMap {
compareFn;
map;
#keys;
constructor(compareFn) {
this.compareFn = compareFn;
this.map = new FastMap();
this.#keys = [];
}
get size() {
return this.map.size;
}
static fromMap(map, compareFn) {
const deterministicMap = new DeterministicMap(compareFn);
for (const [key, value] of map) {
deterministicMap.set(key, value);
}
return deterministicMap;
}
set(key, value) {
if (!this.map.has(key)) {
// Binary search for insertion position
let left = 0, right = this.#keys.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (this.compareFn(this.#keys[mid], key) < 0) {
left = mid + 1;
}
else {
right = mid;
}
}
this.#keys.splice(left, 0, key);
}
this.map.set(key, value);
}
get(key) {
return this.map.get(key);
}
*entries() {
for (const key of this.#keys) {
yield [key, this.map.get(key)];
}
}
*keys() {
yield* this.#keys;
}
*values() {
for (const key of this.#keys) {
const value = this.map.get(key);
if (value === undefined && !this.map.has(key)) {
throw new Error('Value not found');
}
yield value;
}
}
has(key) {
return this.map.has(key);
}
delete(key) {
if (this.map.has(key)) {
this.map.delete(key);
// Binary search to find the key's index
let left = 0, right = this.#keys.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const cmp = this.compareFn(this.#keys[mid], key);
if (cmp === 0) {
// Found it, remove at this index
this.#keys.splice(mid, 1);
return true;
}
else if (cmp < 0) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
}
return false;
}
clear() {
this.map.clear();
this.#keys = [];
}
[Symbol.dispose]() {
this.clear();
}
forEach(callback) {
for (const key of this.#keys) {
const value = this.map.get(key);
callback(value, key, this);
}
}
*[Symbol.iterator]() {
for (const key of this.#keys) {
yield [key, this.map.get(key)];
}
}
}
//# sourceMappingURL=DeterministicMap.js.map