feat(SnowflakeUtil): allow snowflakes to be generated dynamically (#2459)

This commit is contained in:
SpaceEEC
2018-04-17 16:00:18 +02:00
committed by Isabella
parent 8551b8936c
commit f6216f3905

View File

@@ -27,12 +27,19 @@ 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;
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
const BINARY = `${(Date.now() - EPOCH).toString(2).padStart(42, '0')}0000100000${(INCREMENT++).toString(2).padStart(12, '0')}`; const BINARY = `${(timestamp - EPOCH).toString(2).padStart(42, '0')}0000100000${(INCREMENT++).toString(2).padStart(12, '0')}`;
return Util.binaryToID(BINARY); return Util.binaryToID(BINARY);
} }