@ickb/utils
Version:
General utilities built on top of CCC
107 lines • 3.07 kB
JavaScript
import { ccc } from "@ckb-ccc/core";
import { gcd } from "./utils.js";
export class Epoch {
constructor(number, index, length) {
Object.defineProperty(this, "number", {
enumerable: true,
configurable: true,
writable: true,
value: number
});
Object.defineProperty(this, "index", {
enumerable: true,
configurable: true,
writable: true,
value: index
});
Object.defineProperty(this, "length", {
enumerable: true,
configurable: true,
writable: true,
value: length
});
}
static from(epochLike) {
if (epochLike instanceof Epoch) {
return epochLike;
}
let { number, index, length } = deStruct(epochLike);
if (length <= 0n) {
throw new Error("Non positive Epoch length");
}
if (index < 0n) {
const n = (-index + length - 1n) / length;
number -= n;
index += length * n;
}
const g = gcd(index, length);
index /= g;
length /= g;
number += index / length;
index %= length;
return new Epoch(number, index, length);
}
static fromHex(hex) {
return Epoch.from(ccc.epochFromHex(hex));
}
toHex() {
const { number, index, length } = this;
return ccc.epochToHex([number, index, length]);
}
compare(other) {
other = Epoch.from(other);
if (this.number < other.number) {
return -1;
}
if (this.number > other.number) {
return 1;
}
const v0 = this.index * other.length;
const v1 = other.index * this.length;
if (v0 < v1) {
return -1;
}
if (v0 > v1) {
return 1;
}
return 0;
}
add(other) {
other = Epoch.from(other);
const number = this.number + other.number;
let index;
let length;
if (this.length !== other.length) {
index = other.index * this.length + this.index * other.length;
length = this.length * other.length;
}
else {
index = this.index + other.index;
length = this.length;
}
return Epoch.from([number, index, length]);
}
sub(other) {
const { number, index, length } = deStruct(other);
return this.add([-number, -index, length]);
}
toUnix(reference) {
const { number, index, length } = this.sub(reference.epoch);
return (reference.timestamp +
epochInMilliseconds * number +
(epochInMilliseconds * index) / length);
}
}
function deStruct(epochLike) {
if (epochLike instanceof Array) {
const [number, index, length] = epochLike;
return {
number,
index,
length,
};
}
return epochLike;
}
const epochInMilliseconds = 14400000n;
//# sourceMappingURL=epoch.js.map