1.0.2 • Published 3 years ago

snowflake-generator v1.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
3 years ago

snowflake-generator

A lightweight Twitter Snowflake generation package utilising TypeScript.


Getting Started

Install the npm package

npm install snowflake-generator

Require the package into your code

const { Generator } = require('snowflake-generator');

Construct a new Snowflake Generator with the EPOCH timestamp in milliseconds

const SnowflakeGenerator = new Generator(1420070400000); 
// Thursday, 1 January 2015 00:00:00

Generate a Snowflake

const Snowflake = SnowflakeGenerator.generate();

Generator (class)

Constructor

new Generator(epoch?: Date|number, shardID?: number);
paramtypeoptionaldefaultdescription
epochDate|numbertrue946684800000The epoch timestamp to generate from.
shardIDnumbertrue1Useful when running multiple generators at the same time to prevent duplicates.

Properties

.EPOCH

The generators epoch timestamp in milliseconds.@type number

.SHARD_ID

The id of the shard running this generator.@type number

.INCREMENT

The current increment iteration this generator is on.@type number

Methods

Generates snowflakes.

Generator.generate(amount?: number, timestamp?: Date|number);
parametertypeoptionaldefaultdescription
amountnumbertrue1Amount of snowflakes to generate, recommended not to go above 1024 or duplicates will arise.
timestampDate|numbertrueDate.nowTimestamp to generate from

@returns bigint|bigint[]

Deconstruct a snowflake to its values using the Generator.epoch.

Generator.deconstruct(snowflake: SnowflakeResolvable);
parameterstypedescription
snowflakeSnowflakeResolvableSnowflake(s) to deconstruct

@returns DeconstructedSnowflake


Types & Interfaces

SnowflakeResolvable

Resolvable value types for a valid Snowflake.

  • string
  • number
  • bigint

DeconstructedSnowflake

Interface of a Snowflake after Generator.deconstruct().

  • snowflake - Snowflake deconstructed from@type bigint
  • timestamp - The timestamp the snowflake was generated@type bigint
  • shard_id - The shard_id used when generating@type bigint
  • increment - The increment of this snowflake@type bigint
  • binary - The 64Bit snowflake binary string@type string

Extra Credit

Generating more than 1024 snowflakes

let snowflakes = [];
let ts = Date.now();
let amount = 20000;
for (let i = 0; i < (amount / 1024); i++) {
    // this could be improved, but is proof of concept.
    let new_amount = i + 1 >= (amount / 1024) ? amount % 1024 : 1024;
    snowflakes = snowflakes.concat(generator.generate(new_amount, ts + i));
}

Note: When parsing this array through a duplication checking function it returns 0 found duplicates.

> console.log(generator) after running script.
> Note: increment == amount.

Generator { epoch: 1420070400000, shard_id: 1, increment: 20000 }
1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago