Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Last active May 1, 2022 18:37
Show Gist options
  • Save fostyfost/0107e9f9a712f240db1de9887c012822 to your computer and use it in GitHub Desktop.
Save fostyfost/0107e9f9a712f240db1de9887c012822 to your computer and use it in GitHub Desktop.
From or to decimal notation
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
const MIN_RADIX = 2
const MAX_RADIX = ALPHABET.length
function chekRadix(radix: number): void {
if (radix < MIN_RADIX || radix > MAX_RADIX) {
throw new Error(`radix argument must be between ${MIN_RADIX} and ${MAX_RADIX}`)
}
}
function toDecimalNumber(value: string, radix = MAX_RADIX): number {
chekRadix(radix)
let result = 0
let valueLength = value.length
const lastIndex = valueLength - 1
for (let index = 0; index < valueLength; index += 1) {
result = result + ALPHABET.indexOf(value[lastIndex - index]) * radix ** index
}
return result
}
function fromDecimanNumber(value: number, radix = MAX_RADIX): string {
chekRadix(radix)
if (value === 0) {
return '0'
}
let result = ''
let localValue = value
let prefix = ''
if (value < 0) {
localValue *= -1
prefix = '-'
}
while (localValue > 0) {
result = ALPHABET[localValue % radix] + result
localValue = Math.floor(localValue / radix)
}
return prefix + result
}
console.log('****')
console.log(fromDecimanNumber(1000000000000, 2) === (1000000000000).toString(2))
console.log(toDecimalNumber('1000000000000', 36) === parseInt('1000000000000', 36))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment