deno.land / std@0.224.0 / ulid / mod.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// Copyright 2023 Yoshiya Hinosawa. All rights reserved. MIT license.// Copyright 2017 Alizain Feerasta. All rights reserved. MIT license.// This module is browser compatible.
/** * Utilities for generating and working with * {@link https://github.com/ulid/spec | Universally Unique Lexicographically Sortable Identifiers (ULIDs)}. * * @module */
import { encodeRandom, encodeTime, ENCODING, ENCODING_LEN, monotonicFactory, RANDOM_LEN, TIME_LEN, TIME_MAX, type ULID,} from "./_util.ts";
export type { ULID } from "./_util.ts";
/** * Extracts the timestamp given a ULID. * * @example * ```ts * import { ulid, decodeTime } from "https://deno.land/std@$STD_VERSION/ulid/mod.ts"; * * const x = ulid(150000); * decodeTime(x); // 150000 * ``` */export function decodeTime(id: string): number { if (id.length !== TIME_LEN + RANDOM_LEN) { throw new Error("malformed ulid"); } const time = id .substring(0, TIME_LEN) .split("") .reverse() .reduce((carry, char, index) => { const encodingIndex = ENCODING.indexOf(char); if (encodingIndex === -1) { throw new Error("invalid character found: " + char); } return (carry += encodingIndex * Math.pow(ENCODING_LEN, index)); }, 0); if (time > TIME_MAX) { throw new Error("malformed ulid, timestamp too large"); } return time;}
/** * Generate a monotonically increasing ULID, optionally based on a given * timestamp. * * @example * ```ts * import { monotonicUlid } from "https://deno.land/std@$STD_VERSION/ulid/mod.ts"; * * // Strict ordering for the same timestamp, by incrementing the least-significant random bit by 1 * monotonicUlid(150000); // 000XAL6S41ACTAV9WEVGEMMVR8 * monotonicUlid(150000); // 000XAL6S41ACTAV9WEVGEMMVR9 * monotonicUlid(150000); // 000XAL6S41ACTAV9WEVGEMMVRA * monotonicUlid(150000); // 000XAL6S41ACTAV9WEVGEMMVRB * monotonicUlid(150000); // 000XAL6S41ACTAV9WEVGEMMVRC * * // Even if a lower timestamp is passed (or generated), it will preserve sort order * monotonicUlid(100000); // 000XAL6S41ACTAV9WEVGEMMVRD * ``` */export const monotonicUlid: ULID = monotonicFactory();
/** * Generate a ULID, optionally based on a given timestamp. * * @example * ```ts * import { ulid } from "https://deno.land/std@$STD_VERSION/ulid/mod.ts"; * ulid(); // 01ARZ3NDEKTSV4RRFFQ69G5FAV * * // You can also input a seed time which will consistently give you the same string for the time component * ulid(1469918176385); // 01ARYZ6S41TSV4RRFFQ69G5FAV * ``` */export function ulid(seedTime: number = Date.now()): string { return encodeTime(seedTime, TIME_LEN) + encodeRandom(RANDOM_LEN);}
std

Version Info

Tagged at
3 weeks ago