Skip to content

Instantly share code, notes, and snippets.

@lot224
Created August 24, 2021 13:36
Show Gist options
  • Save lot224/8b388f739d2120f8add7cb5ddd388a7b to your computer and use it in GitHub Desktop.
Save lot224/8b388f739d2120f8add7cb5ddd388a7b to your computer and use it in GitHub Desktop.
Shortens a guid from 36 characters to (22-24) characters
// Inspired By
// https://stackoverflow.com/questions/6213227/fastest-way-to-convert-a-number-to-radix-64-in-javascript
// Haven't Fully Tested or implemented in a prod environment
// Generate Random Value matching a guid
const Guid = (): string => {
return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/gi, () => {
const crypto = require('crypto');
const id = crypto.randomBytes(16).toString("hex")[5];
return id;
});
};
const bits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._~';
const encode = (value: number) => {
if (isNaN(Number(value)) || value == null || value === Number.POSITIVE_INFINITY) throw "Not a valid number";
if (value < 0) throw "Not a positive number."
let bit;
let remainder = value;
let result = '';
while (remainder !== 0) {
bit = remainder % bits.length;
result = bits.charAt(bit) + result;
remainder = Math.floor(remainder / bits.length);
//console.log(bit, result, remainder);
}
return result;
}
const decode = (value: string) => {
const chars = value.split('');
let nResult = 0;
chars.forEach((v, i) => {
nResult = nResult * bits.length + bits.indexOf(v);
});
return nResult;
}
export const Id2Guid = (value: string) => {
const parts = value.split('-');
let groups: string[] = [];
parts.forEach(n => {
groups.push(decode(n).toString(16));
});
groups[0] = groups[0].padStart(8, '0');
groups[1] = groups[1].padStart(12, '0').replace(/(\w{4})(\w{4})(\w{4})/gm, `$1-$2-$3`);
groups[2] = groups[2].padStart(12, '0');
return groups.join('-');
}
export const Guid2Id = (guid: string) => {
if (guid.length !== 36) throw "Guid length is not 36";
const groups = guid.split('-');
if (groups.length !== 5) throw "not a valid guid";
const result = [
encode(parseInt('0x' + groups[0])),
encode(parseInt('0x' + groups[1] + groups[2] + groups[3])),
encode(parseInt('0x' + groups[4]))
];
return result.join('-');
}
// Test
for (var i = 0; i < 100; i++) {
const guid = Guid();
const encoded = Guid2Id(guid);
const decoded = Id2Guid(encoded);
console.log(guid, encoded, encoded.length, decoded, decoded.length, guid === decoded);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment