Created
April 19, 2024 20:52
-
-
Save sebringj/de5942f1106b947918c7f9acfe6ac600 to your computer and use it in GitHub Desktop.
GuidShortener
This file contains hidden or 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
class GuidShortener { | |
public static guidToBase95(guid: string): string { | |
const bigInt = this.hexToBigInt(guid); | |
let base95String = this.bigIntToBase95(bigInt); | |
// Pad the result to ensure it's exactly 20 characters long | |
while (base95String.length < 20) { | |
base95String = ' ' + base95String; // Using space to pad for simplicity | |
} | |
return base95String; | |
} | |
public static base95ToGUID(base95String: string): string { | |
const bigInt = this.base95ToBigInt(base95String); | |
const hexString = this.bigIntToHex(bigInt); | |
return this.formatGUID(hexString); | |
} | |
private static hexToBigInt(hexString: string): bigint { | |
// Remove any hyphens and convert hex string to a BigInt | |
return BigInt(`0x${hexString.replace(/-/g, '')}`); | |
} | |
private static bigIntToBase95(bigInt: bigint): string { | |
const base = 95n; | |
const characters = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)); | |
let result = ''; | |
while (bigInt > 0n) { | |
result = characters[Number(bigInt % base)] + result; | |
bigInt /= base; | |
} | |
return result; | |
} | |
private static base95ToBigInt(base95String: string): bigint { | |
const base = 95n; | |
const characters = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)); | |
let bigInt = 0n; | |
for (let char of base95String.trim()) { | |
bigInt = bigInt * base + BigInt(characters.indexOf(char)); | |
} | |
return bigInt; | |
} | |
private static bigIntToHex(bigInt: bigint): string { | |
// Convert BigInt to hex, remove the '0x' prefix, and pad to 32 characters | |
let hexString = bigInt.toString(16).padStart(32, '0'); | |
return hexString; | |
} | |
private static formatGUID(hexString: string): string { | |
// Insert hyphens to format it as a GUID: 8-4-4-4-12 | |
return `${hexString.slice(0, 8)}-${hexString.slice(8, 12)}-${hexString.slice(12, 16)}-${hexString.slice(16, 20)}-${hexString.slice(20)}`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment