Created
April 1, 2019 14:16
-
-
Save stefanmaric/57a9c55dd51049228aa21a51d412c354 to your computer and use it in GitHub Desktop.
Get a string represnetation of an integer in any base
This file contains hidden or 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
/** | |
* Transform a number to any base based on a provided range. | |
* TODO: doesn't support floats. | |
* @param {number} baseTen A regular, primitive integer number | |
* @param {Array<string>} range And array of characters to represent the positional system. | |
* @returns {string} A representation of the provided number in the positional system provided. | |
*/ | |
const toBase = (baseTen, range = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')) => { | |
if (baseTen % 1 > 0) throw new TypeError('Only integers are supported') | |
if (baseTen === 0) return range[0] | |
let reminder = baseTen | |
let result = '' | |
while (reminder > 0) { | |
result = range[reminder % range.length] + result | |
reminder = (reminder - (reminder % range.length)) / range.length | |
} | |
return result | |
} | |
export default toBase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment