mirror of
https://github.com/danbulant/discord.js
synced 2026-06-05 15:51:31 +00:00
feat(SnowflakeUtil): allow snowflakes to be generated dynamically
This commit is contained in:
parent
44fefdfa49
commit
d9a091f674
1 changed files with 9 additions and 2 deletions
|
|
@ -27,11 +27,18 @@ class SnowflakeUtil {
|
||||||
/**
|
/**
|
||||||
* Generates a Discord snowflake.
|
* Generates a Discord snowflake.
|
||||||
* <info>This hardcodes the worker ID as 1 and the process ID as 0.</info>
|
* <info>This hardcodes the worker ID as 1 and the process ID as 0.</info>
|
||||||
|
* @param {number|Date} [timestamp=Date.now()] Timestamp or date of the snowflake to generate
|
||||||
* @returns {Snowflake} The generated snowflake
|
* @returns {Snowflake} The generated snowflake
|
||||||
*/
|
*/
|
||||||
static generate() {
|
static generate(timestamp = Date.now()) {
|
||||||
|
if (timestamp instanceof Date) timestamp = timestamp.getTime();
|
||||||
|
if (typeof timestamp !== 'number' || isNaN(timestamp)) {
|
||||||
|
throw new TypeError(
|
||||||
|
`"timestamp" argument must be a number (received ${isNaN(timestamp) ? 'NaN' : typeof timestamp})`
|
||||||
|
);
|
||||||
|
}
|
||||||
if (INCREMENT >= 4095) INCREMENT = 0;
|
if (INCREMENT >= 4095) INCREMENT = 0;
|
||||||
const BINARY = `${pad((Date.now() - EPOCH).toString(2), 42)}0000100000${pad((INCREMENT++).toString(2), 12)}`;
|
const BINARY = `${pad((timestamp - EPOCH).toString(2), 42)}0000100000${pad((INCREMENT++).toString(2), 12)}`;
|
||||||
return Long.fromString(BINARY, 2).toString();
|
return Long.fromString(BINARY, 2).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue