number-system-converter/index.js

83 lines
2.7 KiB
JavaScript

const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
function dec_to_base() {
readline.question(`Enter a number to convert: `, num => {
num = parseInt(num);
readline.question(`Enter a number new base: `, base => {
base = parseInt(base);
try {
new_num = num.toString(base);
console.log(`\nBASE 10: ${num} ==> BASE ${base}: ${new_num}`);
} catch (RangeError) {
console.log(`Base is not in the range of 2 to 36.\nExiting...`);
} finally {
readline.close();
};
});
});
};
function base_to_dec() {
readline.question(`Enter a number to convert: `, num => {
readline.question(`Enter the number's base: `, base => {
base = parseInt(base);
try {
new_num = parseInt(num, base);
console.log(`\nBASE ${base}: ${num} ==> BASE 10: ${new_num}`);
} catch (RangeError) {
console.log(`Base is not in the range of 2 to 36.\nExiting...`);
}
finally {
readline.close();
};
});
});
};
function base_to_base() {
readline.question(`Enter a number to convert: `, num => {
readline.question(`Enter the number's base: `, base => {
base = parseInt(base);
readline.question(`Enter a number new base: `, new_base => {
new_base = parseInt(new_base);
try {
let dec_num = parseInt(num, base);
let new_num = dec_num.toString(new_base);
console.log(`\nBASE ${base}: ${num} ==> BASE ${new_base}: ${new_num}`);
} catch (RangeError) {
console.log(`One or more bases is not in the range of 2 to 36.\nExiting...`);
}
finally {
readline.close();
};
});
});
});
};
readline.question(`Choose an option:\n\n1) decimal to any base\n2) any base to decimal\n3) any base to any base\n`, choice => {
if (choice * 1.0) {
choice = parseInt(choice);
switch (choice) {
case 1:
dec_to_base();
break;
case 2:
base_to_dec();
break;
case 3:
base_to_base();
break;
default:
console.log("Please choose a proper entry.");
readline.close();
break;
};
} else {
console.log("Please enter a number.");
readline.close();
};
});