UNPKG

891 BJavaScriptView Raw
1/**
2 * All timestamp has to be generated through use of this function. All stored
3 * and networked timestamps are in seconds and not in milliseconds!
4 *
5 * @returns {number} Number of seconds since 01-01-1970 00:00:00 UTC
6 */
7export function now() {
8 return Date.now() / 1000;
9}
10
11const METRIC_THRESHOLD = 2n ** 255n;
12
13export function compareDistance(a, b) {
14 if (a.length !== 32 || b.length !== 32) {
15 throw new Error('Invalid parameter length for `compareDistance`');
16 }
17
18 a = BigInt(`0x${a.toString('hex')}`);
19 b = BigInt(`0x${b.toString('hex')}`);
20
21 const delta = b - a;
22 if (delta === 0n) {
23 return 0;
24 }
25
26 const absDelta = delta < 0 ? -delta : delta;
27
28 if (delta > 0n) {
29 if (absDelta < METRIC_THRESHOLD) {
30 return -1;
31 } else {
32 return 1;
33 }
34 } else {
35 if (absDelta < METRIC_THRESHOLD) {
36 return 1;
37 } else {
38 return -1;
39 }
40 }
41}