Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Created December 3, 2024 20:53
Show Gist options
  • Save jamiebuilds/4bd909972df987166e02d08d2322fcea to your computer and use it in GitHub Desktop.
Save jamiebuilds/4bd909972df987166e02d08d2322fcea to your computer and use it in GitHub Desktop.
//
// Coding challenge:
//
// Write a `mockUuid()` function that each time its called returns
// an incrementing integer formatted as a UUID.
//
// Then optimize the function to be as fast as you possibly can.
//
// UUID format:
// XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
// - 32 digits in sections of 8-4-4-4-12
// - each digit is a hexadecimal number (0123456789ABCDEF)
//
// This means every possible UUID can actually be
// represented as a 32-byte (not bit) integer (0 to 32^16).
//
// 00000000-0000-0000-0000-000000000000 is 0
// 00000000-0000-0000-0000-000000000001 is 1
// ...
// FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFE is 1208925819614629174706175
// FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF is 1208925819614629174706176
let i = 0n // bigint
/** @returns {string} */
function mockUuid() {
let id = i++
let hex = id.toString(16)
// implement me: format as uuid...
}
for (let i = 0; i < 0xFFF) {
mockUuid()
}
// "00000000-0000-0000-0000-000000000000" - 0
// "00000000-0000-0000-0000-000000000001" - 1
// ...
// "00000000-0000-0000-0000-00000000000e" - 14
// "00000000-0000-0000-0000-00000000000f" - 15
// "00000000-0000-0000-0000-000000000010" - 16
// "00000000-0000-0000-0000-000000000011" - 17
// ...
// "00000000-0000-0000-0000-0000000000fe" - 254
// "00000000-0000-0000-0000-0000000000ff" - 255
// "00000000-0000-0000-0000-000000000100" - 256
// "00000000-0000-0000-0000-000000000101" - 257
// ...
// "00000000-0000-0000-0000-000000000ffe" - 4094
// "00000000-0000-0000-0000-000000000fff" - 4095
// Say we need to generate a *lot* of UUIDs very very quickly...
// What would be the fastest way of generating all these strings
// Hints:
// - id.toString(16).padStart(32, '0') will give you a UUID without dashes
// - id.slice(0, 8) and id.slice(8, 12) will give you the first two sections of the uuid
// - HOWEVER... we know we always incrementing by 1.
// - AND... most of the time (but not always) only one digit is changing.
// - How could we use this information to produce new strings faster?
// How to measure:
// Count the total program execution time not just the loop of mockUuid().
// So precomputing a bunch of values will count toward your total time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment