In JavaScript you can generate a string from a number like this:
(123).toString(36) // => "3f"
If you try to do arbitrary base:
(123).toString(40)
You get
Uncaught RangeError: toString() radix argument must be between 2 and 36
at Number.toString (<anonymous>)
at <anonymous>:1:7
Wondering how to do this to generate a string given an arbitrary alphabet. So say you have this alphabet:
abcdefghijklmnopqrstuvwxyz0123456789+-
Then it would be like:
toString(123, 'abcdefghijklmnopqrstuvwxyz0123456789+-')
And it would print something out (I have no idea what) such as 3+, picking from the alphabet.
Wondering how to do this in JavaScript, not sure if the "radix" has anything to do with it. Thank you.
Update: Looking how to reverse it as well, aka fromString(string).
While you asked for a parseInt for an arbitrary length, you could use the given string and reduce it by multiplying the former reduce value with the code length and adding the numerical value of the position of the code character.
Additional is the toString function supplied.
function parseInt(value, code) {
return [...value].reduce((r, a) => r * code.length + code.indexOf(a), 0);
}
function toString(value, code) {
var digit,
radix= code.length,
result = '';
do {
digit = value % radix;
result = code[digit] + result;
value = Math.floor(value / radix);
} while (value)
return result;
}
console.log(parseInt('dj', 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
console.log(toString(123, 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
console.log(parseInt('a', 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
console.log(toString(0, 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can simulate that doing:
const toString = (number, alphabet) => {
let result = "";
while (number) {
const digit = number%alphabet.length;
number = (number/alphabet.length)|0;
result = alphabet[digit] + result;
}
return result || alphabet[0];
}
//////////////////// For the opposite, you can use this:
const fromStringBuilder = (alphabet) => {
const alphabetKeys = {};
for (let i = 0; i < alphabet.length; i++) {
alphabetKeys[alphabet[i]] = i;
}
return (string) => {
return [...string].reduce((a,v) => a * alphabet.length + alphabetKeys[v],0);
}
}
//////////////////// Here you have example usage:
toAlphabet = (number) => toString(number, 'abcdefghijklmnopqrstuvwxyz0123456789+-')
fromAlphabet = fromStringBuilder('abcdefghijklmnopqrstuvwxyz0123456789+-')
console.log(fromAlphabet("3+")) // 1138
console.log(toAlphabet(1138)) // "3+"
console.log(toAlphabet(fromAlphabet("3+"))) // "3+"
Note: alphabet must be a string with at least two chars. Otherwise, the loop will be infinite.
Note 2: you have to pass the alphabet in the reverse order from your example to achieve the same exact output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With