From f6216f3905adc2d01532c0fd6ad1e0fadec6d842 Mon Sep 17 00:00:00 2001 From: SpaceEEC Date: Tue, 17 Apr 2018 16:00:18 +0200 Subject: [PATCH] feat(SnowflakeUtil): allow snowflakes to be generated dynamically (#2459) --- 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 27f9f7440..00f22d06f 100644 --- a/src/util/Snowflake.js +++ b/src/util/Snowflake.js @@ -27,12 +27,19 @@ 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; // 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); }