Convert UUIDs to (shorter) class names

node v0.12.18
version: 1.1.0
endpointsharetweet
const assert = require('assert'); const uuid = require("uuid-v4"); // 10 digits + 26 uppercase + 26 lowercase + 1 underscore // Note that we could use a hyphen also, but converting to base-63 leads to more 0s const POSSIBLE_CHARS = 63; const getBase63CharacterFromInt = (int) => { if (int === 62) return '_'; // Numbers: 48-57 if (int < 10) return String.fromCharCode(int + 48); return int < 36 ? // Uppercase letters: 65-90 (starting from 10; 65-10=55) String.fromCharCode(int + 55) : // Lowercase letters: 97-121 (starting from 36; 97-36=61) String.fromCharCode(int + 61); }; assert.strictEqual(getBase63CharacterFromInt(0), '0', 'Doesn’t convert correctly at start of numeric range'); assert.strictEqual(getBase63CharacterFromInt(9), '9', 'Doesn’t convert correctly at end of numeric range'); assert.strictEqual(getBase63CharacterFromInt(10), 'A', 'Doesn’t convert correctly at start of uppercase alpha range'); assert.strictEqual(getBase63CharacterFromInt(35), 'Z', 'Doesn’t convert correctly at end of uppercase alpha range'); assert.strictEqual(getBase63CharacterFromInt(36), 'a', 'Doesn’t convert correctly at start of lowercase alpha range'); assert.strictEqual(getBase63CharacterFromInt(61), 'z', 'Doesn’t convert correctly at end of lower case alpha range'); assert.strictEqual(getBase63CharacterFromInt(62), '_', 'Doesn’t convert 62 to underscore'); // Use a convert base-10 number algorithm to create base-63 classname const convertIntToClassName = (int) => { let className = ''; while (int > 1) { const modulo = int % POSSIBLE_CHARS; className = `${getBase63CharacterFromInt(modulo)}${className}`; int = (int - modulo) / POSSIBLE_CHARS; } return className; } // Strip the non-numeric parts of the id to make a base-10 number, then convert it to a base-63 alphanumeric representation const NON_NUMERIC = /[^\d]/g; const convertUuidToClassName = (id) => `c${convertIntToClassName(parseInt(id.replace(NON_NUMERIC, ''), 10))}`; let i = 0; let classNames = []; const makeNew = () => { if (i >= 100) { console.log(classNames); return; } i++; classNames.push(convertUuidToClassName(uuid())); setTimeout(makeNew); }; makeNew(); 'it begins';
Loading…

no comments

    sign in to comment