Base 36 in JavaScript: Compression and Decompression

Day 16 of me reading random and basic but important coding facts....... Today I read about Base 36 in JS numbers...... JS engine has a native ability to handle Base 36. Base 36 is a numbering system that uses digits 0-9 and letters a-z ....means total of 36 symbols. This allows us to pack a lot more value into fewer characters because z in Base 36 is equal to 35 in decimal......... Here how it does Compression and decompression......... Use the .toString() method. const myNumber = 46656; const compressed = myNumber.toString(36); console.log(compressed); // Output: "1000" // (It shrank 5 digits down to 4 characters) Use parseInt with the second argument. const id = "1000"; const original = parseInt(id, 36); console.log(original); // Output: 46656 now how it is internally implemented......it's quite simple by the way...... It doesn't just lookup values, it uses optimized math...... Divide the number by 36. Take the remainder (0-35). Map that remainder to a character. Repeat until the number hits 0. engine doesn't use a slow dictionary object like { 10: 'a' }. It uses ASCII codes If remainder is 0-9: It adds 48. If remainder is 10-35: It subtracts 10 and adds 97. there are lots of real world use cases of this feature.... and the best I read were.... URL Shortening: If you have a database ID like 1048576, converting it to Base 36 gives you m2s0. This is perfect for cleaner, shorter URLs (like Youtube video IDs). Generating Random IDs: A quick way to generate a random alphanumeric string: Math.random().toString(36).substring(2); but with every advantage there exists some disadvantages..... It is not human friendly:- "1ka" is harder for a human to type or remember than "2026". Collision Risk: If we use the Math.random() trick above, we can get duplicates...... Keep Learning!!!!! #JavaScript #Coding #WebDevelopment #SoftwareEngineering #FrontEndDev

To view or add a comment, sign in

Explore content categories