import { SnowflakeResolvable } from "../types/snowflake";
import SnowflakeGen from "../lib/snowflake";
import Config from "./config";
/**
* Snowflake class
*/
class Snowflake {
readonly time: Date;
readonly machine: number;
readonly instance: number;
readonly id: number;
// @ts-ignore
private original: string;
private originalBigint?: bigint;
/**
* @param {number} id Snowflake data to fetch from
*/
constructor(id: SnowflakeResolvable) {
if(typeof id === "string") id = BigInt(id);
if(typeof id === "bigint") {
var shifted = id >> BigInt(22);
// shifted += BigInt(ANIMASHER_EPOCH);
this.time = new Date(Number(shifted));
this.machine = Number((id & BigInt(0x3E0000)) >> BigInt(17));
this.instance = Number((id & BigInt(0x1F000)) >> BigInt(12));
this.id = Number(id & BigInt(0xFFF));
} else if(id instanceof Snowflake) {
this.time = id.time;
this.machine = id.machine;
this.instance = id.instance;
this.id = id.id;
return id;
} else {
throw new Error("Unsupported type for snowflake - " + typeof id);
}
this.original = id.toString();
if(typeof id === "bigint") this.originalBigint = id;
}
/**
* @return {string} snowflake
*/
getSnowflake() {
return this.original!;
}
/**
* @return {string} snowflake
*/
toString(): string {
return this.getSnowflake();
}
private static generator = new SnowflakeGen({
mid: Config.machine,
iid: Config.instance
});
/**
* @return {Snowflake}
*/
static newSnowflake() {
const s = this.generator.gen();
return new Snowflake(BigInt(s));
}
/**
* Creates a JSON-compatible object
* @return {Object}
*/
toJSON() {
return this.getSnowflake();
}
/**
* Converts to a bigint
* @return {bigint}
*/
toBigInt() {
if(this.originalBigint) return this.originalBigint;
return BigInt(this.getSnowflake());
}
}
export default Snowflake;
Source