Currently there are these two functions for converting an integer to a string in a given character set, and back:
const parseInt = (value, code) => {
return value.split('').reduce((r, a) => r * code.length + code.indexOf(a), 0)
}
const 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;
}
toString(115, 'abcdefghijklmnop') // => 'hd'
However, they are inefficient from the standpoint of if this were C or things with static memory allocation. The result = code[digit] + result
is building a string one character at a time, completely regenerating the character chain on each iteration.
How can this be streamlined so it:
- Perhaps precomputes the size of the array in advance, and
- Generates the character string from left to right rather than in reverse?
And how could you change the parseInt
function to account for reversing the toString
after toString
is reimplemented?
Also is it possible to get rid of the Math.floor
? If not, that is okay but would hope there is potentially a way. If there is a way to get rid of Math.floor
if certain constraints on character-set-length or input size is adhered to, please mention in the comments and I may ask another question for that. Thank you!
Obviously you can reverse the function (somehow) and add a .reverse()
on the character array, but ideally we could optimize with subtracting steps (and rearranging), rather than adding extra steps. This is to be highly optimized.
Note. The solution algorithm output doesn't have to be the same as the above algorithms. The output can be reversed, that is okay. Just looking for a highly optimized variant of this function that generally accomplishes the same thing: encoding an integer into a string using a character set, and reversing it to get the integer back.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…