Skip to content

Instantly share code, notes, and snippets.

@railsstudent
Created January 31, 2017 02:50
Show Gist options
  • Save railsstudent/9887acd486214570f9425d1a06ad38d2 to your computer and use it in GitHub Desktop.
Save railsstudent/9887acd486214570f9425d1a06ad38d2 to your computer and use it in GitHub Desktop.
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