javascript
javascript copied to clipboard
First and Last IDs for Timestamp
Is it possible to obtain the first and last lexicography sorted IDs for a timestamp?
If I understand correctly, it seems possible to get the first ID with monotonicFactory()
.
However, I'm not sure how to go about obtaining the last ID.
Any help would be much appreciated. 👍
Upon further investigation, it seems fairly straightforward, without the use of monotonicFactory()
.
// External Modules
import { encodeTime } from 'ulid';
// Constants
const ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const TIME_LEN = 10;
const RANDOM_LEN = 16;
function generateTimeBounds(timestamp: number)
{
const timeComponent = encodeTime(timestamp, TIME_LEN);
const first = timeComponent + generateRandomnessBound('first');
const last = timeComponent + generateRandomnessBound('last');
return { first, last };
};
function generateRandomnessBound(bound: 'first' | 'last')
{
const boundCharacter = bound === 'first' ? ENCODING[0] : ENCODING[ENCODING.length - 1];
let randomness = '';
for (let character = 0; character < RANDOM_LEN; character++)
{
randomness += boundCharacter;
};
return randomness;
};
Perhaps this could be a useful addition as a helper method in the library?
My use case is to retrieve records from a database which, according to their ID, occur within a time period. For instance, records which occur between two dates represented by timestamps.
The "smallest" ulid for a particular timestamp will always be xxxxxxxx0000000000000000
, and the "largest" will always be xxxxxxxxxxZZZZZZZZZZZZZZZZ
Yep. That's what my code does, just dynamically using the ENCODING
string.
This is a very useful helper function when working with time ranges. It would be nice to have it as part of the module, rather than having to redeclare it in every project where it is needed.
If it would be welcome, I could submit a pull request for this.
It would also be nice ulid's TIME_LEN
variable was exported, so calling encodeTime()
could be guaranteed to use the same parameters as ulid's internals.