Created
January 31, 2017 02:50
-
-
Save railsstudent/9887acd486214570f9425d1a06ad38d2 to your computer and use it in GitHub Desktop.
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
function convert(input, source, target) { | |
if (source === target) { | |
return input; | |
} | |
// Compute the value of the input in source base | |
// then convert it to value in target base | |
let sourceValue = input.split('').reverse().reduce( (acc, val, digitPos) => { | |
return acc + Math.pow(source.length, digitPos) * source.indexOf(val); | |
}, 0); | |
if (sourceValue === 0) { | |
return target[0]; | |
} | |
// convert source value to value in target base | |
let targetValue = ''; | |
while (sourceValue > 0) { | |
targetValue += target[sourceValue % target.length]; | |
sourceValue = Math.floor(sourceValue / target.length); | |
} | |
return targetValue.split('').reverse().join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment