Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Created April 1, 2019 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanmaric/57a9c55dd51049228aa21a51d412c354 to your computer and use it in GitHub Desktop.
Save stefanmaric/57a9c55dd51049228aa21a51d412c354 to your computer and use it in GitHub Desktop.
Get a string represnetation of an integer in any base
/**
* 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