Created
April 20, 2023 05:09
-
-
Save thekoushik/41e157294f34c8915a6a18fd38dcaff9 to your computer and use it in GitHub Desktop.
Custom Base Encoder and Decoder
This file contains 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
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; | |
/** | |
* Encodes a positive integer to a string using a | |
* list of unique characters. | |
* | |
* @param {number} num - Positive integer | |
* @returns {string} Encoded string | |
*/ | |
function encode(num) { | |
if (isNaN(num)) throw new Error("Not a number"); | |
if (num<0) throw new Error("Negative integer not supported"); | |
const base = chars.length; | |
let result = ''; | |
let accumulator = num; | |
do { | |
const divide = Math.floor(accumulator / base); | |
const rem = accumulator % base; | |
result = `${chars.charAt(rem)}${result}`; | |
if (divide) { | |
result = `${chars.charAt(divide)}${result}`; | |
} | |
accumulator = divide; | |
} while(accumulator>=base); | |
return result; | |
} | |
/** | |
* Decodes an encoded string to a positive integer using | |
* the same list of unique characters used for encoding. | |
* | |
* @param {string} str - Encoded string | |
* @returns {number} Decoded integer | |
*/ | |
function decode(str) { | |
const base = chars.length; | |
const items = `${str}`.split(''); | |
let num = chars.indexOf(items[0]); | |
for(let i = 1;i<items.length; i++) { | |
num = (base * num) + chars.indexOf(items[i]); | |
} | |
return num; | |
} | |
console.log(encode(240826));//wow | |
console.log(decode('wow'));//240826 | |
// (function benchmark(){ | |
// console.time(); | |
// for(let i=1;i<=10000;i++) { | |
// const result = decode(encode(i)); | |
// if (result !== i) throw new Error("Algo failed"); | |
// } | |
// console.timeEnd(); | |
// // 8.8ms | |
// })() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment