Skip to content

Instantly share code, notes, and snippets.

@tybro0103
Created April 19, 2020 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tybro0103/9b7dc85342279d88ad297da370cecaca to your computer and use it in GitHub Desktop.
Save tybro0103/9b7dc85342279d88ad297da370cecaca to your computer and use it in GitHub Desktop.
URL friendly IDs via Modular Multiplicative Inverse
// https://www.reddit.com/r/PostgreSQL/comments/6gw866/best_practice_for_id_system_that_is_obscure_for/diu8cr1/
// https://planetcalc.com/3311/
const [a, b, modulo, radix] = [204021643231n, 975874032671n, 1000000000000n, 36];
const encode = (plainId) => ((BigInt(plainId) * a) % modulo).toString(radix);
const decode = (encodedId) => (BigInt(parseInt(encodedId, radix)) * b) % modulo;
for (let i = 1; i <= 20; i++) {
console.log(`${i} | ${encode(i)} | ${decode(encode(i))}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment