Last active
September 8, 2020 08:52
-
-
Save krowter/c8d32e4bd23d0c75632a88fca12d861e to your computer and use it in GitHub Desktop.
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
/** | |
* range of available symbols for maximum radix (i.e. 61) | |
* @type {string} | |
*/ | |
const range = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
/** | |
* converts JavaScript number from other bases to decimal | |
* | |
* @param {number} value number to be converted | |
* @param {number} sourceBase base of first param | |
* @returns {number} first param in decimal | |
*/ | |
const convertToDecimal = (value, sourceBase) => | |
String(value) | |
.split("") | |
.reverse() | |
.reduce((sum, num, index) => { | |
const decimal = range.indexOf(num) * sourceBase ** index; | |
return sum + decimal; | |
}, 0); | |
/** | |
* converts JavaScript number from decimal to other bases | |
* | |
* @param {number} decimalValue number to be converted | |
* @param {number} targetBase base of the return value | |
* @returns {number} first param in target base | |
* | |
*/ | |
const convertFromDecimal = (decimalValue, targetBase) => { | |
let result = ""; | |
while (decimalValue > 0) { | |
result = range[decimalValue % targetBase] + result; | |
decimalValue = Math.floor(decimalValue / targetBase); | |
} | |
return result; | |
}; | |
/** | |
* converts JavaScript number from and to any bases (read max radix in 1st line) | |
* | |
* @param {number} value number to be converted | |
* @param {number} sourceBase base of first param * | |
* @param {number} targetBase base of the return value | |
* @returns {number} first param in target base | |
* @example convertBase(255, 10, 16) | |
* //=> "ff" | |
*/ | |
const convertBase = (value, sourceBase, targetBase) => { | |
let decimalValue; | |
if (sourceBase === 10) { | |
decimalValue = value; | |
} else { | |
decimalValue = convertToDecimal(value, sourceBase); | |
} | |
if (targetBase === 10) return decimalValue; | |
return convertFromDecimal(decimalValue, targetBase); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment