From d9a091f674eb892c4c2b4112e275524e49a1ee8a Mon Sep 17 00:00:00 2001 From: SpaceEEC Date: Fri, 27 Apr 2018 20:34:48 +0200 Subject: [PATCH] feat(SnowflakeUtil): allow snowflakes to be generated dynamically --- src/util/Snowflake.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/util/Snowflake.js b/src/util/Snowflake.js index f16839108..2775266dc 100644 --- a/src/util/Snowflake.js +++ b/src/util/Snowflake.js @@ -27,11 +27,18 @@ class SnowflakeUtil { /** * Generates a Discord snowflake. * This hardcodes the worker ID as 1 and the process ID as 0. + * @param {number|Date} [timestamp=Date.now()] Timestamp or date of the snowflake to generate * @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; - 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(); }