number-system-converter/index.js

83 lines
2.7 KiB
JavaScript
Raw Normal View History

2022-02-08 22:59:39 -05:00
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
2022-02-09 14:49:55 -05:00
});
2022-02-08 22:59:39 -05:00
2022-02-09 14:06:04 -05:00
function dec_to_base() {
readline.question(`Enter a number to convert: `, num => {
2022-02-09 14:49:55 -05:00
num = parseInt(num);
2022-02-09 14:06:04 -05:00
readline.question(`Enter a number new base: `, base => {
2022-02-09 14:49:55 -05:00
base = parseInt(base);
2022-02-09 14:06:04 -05:00
try {
2022-02-09 14:49:55 -05:00
new_num = num.toString(base);
2022-02-09 14:06:04 -05:00
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 {
2022-02-09 14:49:55 -05:00
readline.close();
};
});
});
};
2022-02-09 14:06:04 -05:00
function base_to_dec() {
readline.question(`Enter a number to convert: `, num => {
readline.question(`Enter the number's base: `, base => {
2022-02-09 14:49:55 -05:00
base = parseInt(base);
2022-02-09 14:06:04 -05:00
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 {
2022-02-09 14:49:55 -05:00
readline.close();
};
});
});
};
2022-02-09 14:06:04 -05:00
function base_to_base() {
readline.question(`Enter a number to convert: `, num => {
readline.question(`Enter the number's base: `, base => {
2022-02-09 14:49:55 -05:00
base = parseInt(base);
2022-02-09 14:06:04 -05:00
readline.question(`Enter a number new base: `, new_base => {
2022-02-09 14:49:55 -05:00
new_base = parseInt(new_base);
2022-02-09 14:06:04 -05:00
try {
2022-02-09 14:49:55 -05:00
let dec_num = parseInt(num, base);
let new_num = dec_num.toString(new_base);
2022-02-09 14:06:04 -05:00
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 {
2022-02-09 14:49:55 -05:00
readline.close();
};
});
});
});
};
2022-02-09 14:06:04 -05:00
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:
2022-02-09 14:49:55 -05:00
dec_to_base();
2022-02-09 14:06:04 -05:00
break;
case 2:
2022-02-09 14:49:55 -05:00
base_to_dec();
2022-02-09 14:06:04 -05:00
break;
case 3:
2022-02-09 14:49:55 -05:00
base_to_base();
2022-02-09 14:06:04 -05:00
break;
default:
2022-02-09 14:49:55 -05:00
console.log("Please choose a proper entry.");
readline.close();
2022-02-09 14:06:04 -05:00
break;
2022-02-09 14:49:55 -05:00
};
2022-02-09 14:06:04 -05:00
} else {
2022-02-09 14:49:55 -05:00
console.log("Please enter a number.");
readline.close();
};
});