javascript icon indicating copy to clipboard operation
javascript copied to clipboard

First and Last IDs for Timestamp

Open ChrisTalman opened this issue 5 years ago • 4 comments

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. 👍

ChrisTalman avatar May 06 '19 22:05 ChrisTalman

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.

ChrisTalman avatar May 07 '19 16:05 ChrisTalman

The "smallest" ulid for a particular timestamp will always be xxxxxxxx0000000000000000, and the "largest" will always be xxxxxxxxxxZZZZZZZZZZZZZZZZ

alizain avatar Oct 10 '19 19:10 alizain

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.

ChrisTalman avatar Nov 13 '19 21:11 ChrisTalman

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.

spiffytech avatar Jan 15 '21 19:01 spiffytech