1
1
const { Snowflake } = require ( '../build/Release/snowflake' ) ;
2
2
3
3
const CUSTOM_EPOCH = 1546300800000 ; // 01-01-2019
4
+ const MAX_MACHINE_ID = ( 1 << 12 ) - 1 ;
4
5
5
6
interface Config {
6
7
customEpoch ?: number ;
@@ -18,7 +19,7 @@ const initConfig: Config = {
18
19
* of a unique 64 bit time sortable id and a method for retreiving
19
20
* time of creation for the ids
20
21
*
21
- * @param {config } [customEpoch = 1546300800000] A 32 bit long custom epoch
22
+ * @param {config } config
22
23
* in ms, defaults to 1546300800000 (01-01-2019)
23
24
*
24
25
* ```
@@ -30,22 +31,22 @@ const initConfig: Config = {
30
31
export class UniqueID {
31
32
private _CUSTOM_EPOCH : number ;
32
33
private _snowflake : any ;
33
- private _MACHINE_ID ? : number ;
34
+ private _MACHINE_ID : number ;
34
35
private returnNumber = true ;
35
36
36
37
constructor ( config : Config = initConfig ) {
37
38
this . _CUSTOM_EPOCH = config . customEpoch || CUSTOM_EPOCH ;
38
- this . _MACHINE_ID = config . machineID ;
39
39
this . returnNumber = ! ! config . returnNumber ;
40
40
41
- if ( ( this . _MACHINE_ID !== undefined ) && ! isNaN ( this . _MACHINE_ID ) ) {
42
- if ( ! Number . isInteger ( this . _MACHINE_ID ) ) throw Error ( "Machine Id should be a decimal number" ) ;
43
- if ( this . _MACHINE_ID > ( 1 << 12 ) - 1 ) throw Error ( "Maximum value of machine id can be 2^12 - 1 (4095)" )
44
- this . _snowflake = new Snowflake ( this . _CUSTOM_EPOCH , this . _MACHINE_ID ) ;
45
- return ;
46
- }
41
+ // A 12 bit machine id, if not passed in then a random id will be used
42
+ // Ternary operator was used to make sure "0" isn't considered to be falsy.
43
+ this . _MACHINE_ID = config . machineID !== undefined ? config . machineID : Math . floor ( Math . random ( ) * MAX_MACHINE_ID ) ;
47
44
48
- this . _snowflake = new Snowflake ( this . _CUSTOM_EPOCH ) ;
45
+ // Check if the number is satisfies all the conditions
46
+ if ( ! Number . isInteger ( this . _MACHINE_ID ) ) throw Error ( "Machine Id should be a decimal number" ) ;
47
+ if ( this . _MACHINE_ID > MAX_MACHINE_ID ) throw Error ( "Maximum value of machine id can be 2^12 - 1 (4095)" )
48
+
49
+ this . _snowflake = new Snowflake ( this . _CUSTOM_EPOCH , this . _MACHINE_ID ) ;
49
50
}
50
51
51
52
/**
@@ -78,7 +79,21 @@ export class UniqueID {
78
79
return this . _snowflake . getTimestampFromID ( id ) ;
79
80
}
80
81
82
+ /**
83
+ * Retrieves the 12 bit machine id where the id was generated,
84
+ * irrespective of the machine it was generated on.
85
+ * @param id
86
+ */
81
87
getMachineIDFromID ( id : bigint | string ) : number {
82
88
return this . _snowflake . getNodeIDFromID ( id ) ;
83
89
}
90
+
91
+ /**
92
+ * Machine ID of the current machine. This ID is of 12 bit.
93
+ * This can be either provided by the user (preferred) or will be assigned
94
+ * randomly.
95
+ */
96
+ get machineID ( ) {
97
+ return this . _MACHINE_ID ;
98
+ }
84
99
}
0 commit comments