Short URL / Password Base Conversion Generator

This JavaScript project implements base conversion to generate short URLs or passwords from numerical IDs. It converts a random base-10 number to a custom base-32 representation, using a character set that avoids ambiguous letters (e.g., no ‘0’ vs ‘O’, ‘1’ vs ’l’). I enjoyed building this, exploring number systems and imagining a URL shortener backend where database indices translate to compact, readable codes. Concepts like removing similar-looking characters or using distinguishable fonts enhance usability, making short links or passwords more user-friendly and error-resistant.
Project Overview
The core is a convertBase function that transforms numbers between bases. It generates a random number, converts it to base 31, and displays the result. This mimics URL shorteners like bit.ly, where long IDs become short strings.
Why base conversion? Higher bases use fewer characters for large numbers, ideal for short URLs. Base 32 (31 chars) balances brevity and readability.
Code Breakdown
The function handles conversion:
function convertBase(value, from_base, to_base) {
var base10 = '0123456789+/'.split('');
var base32 = '0123456789bcdfghjklmnpqrstvwxyz+/'.split(''); // Avoids ambiguous chars
var from_range = base10.slice(0, 10);
var to_range = base32.slice(0, 31);
var dec_value = value.split('').reverse().reduce(function (carry, digit, index) {
if (from_range.indexOf(digit) === -1) throw new Error('Invalid digit `'+digit+'` for base '+from_base+'.');
return carry += from_range.indexOf(digit) * (Math.pow(from_base, index));
}, 0);
var new_value = '';
while (dec_value > 0) {
new_value = to_range[dec_value % to_base] + new_value;
dec_value = (dec_value - (dec_value % to_base)) / to_base;
}
return new_value || '0';
}
It parses the input to decimal, then converts to the target base using modulo and division.
Usage example:
var randnumb = Math.floor(Math.random() * 1000000) + "";
alert("numb: " + randnumb + " base 30: " + convertBase(randnumb, 10, 31));
Generates a random number and its base-31 equivalent.
Concepts Explored
Building this sparked ideas for a URL shortener:
- Backend: Store URLs with auto-increment IDs. Convert ID to base-32 for short code (e.g., ID 1000000 -> short string).
- Database Integration: Use MySQL or MongoDB for ID-to-URL mapping.
- Ambiguous Characters: Excluded ‘o’, ‘i’, ’l’ to prevent confusion. Alternative: fonts like Courier for clear distinction.
- Base Systems: Base-32 uses 31 chars (0-9, letters minus ambiguous ones). Higher bases shorten codes but increase errors.
This could extend to password generators, using bases for memorable, unique strings.
Enjoyment and Insights
I loved pondering number systems and practical applications. It’s a simple yet powerful concept, turning math into useful tools. Future enhancements could include UI for input/output or database hooks.