Created
April 19, 2020 20:42
-
-
Save tybro0103/9b7dc85342279d88ad297da370cecaca to your computer and use it in GitHub Desktop.
URL friendly IDs via Modular Multiplicative Inverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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