chs-console-emulation
Version:
Emulate CodeHS console I/O functions for use in NodeJS environment.
96 lines (84 loc) • 3.41 kB
JavaScript
//=========================================================
// chs-console-emulation.js
//
// ▄ ▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄
// ▐░▌ ▐░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌
// ▐░▌ ▐░▌▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀▀▀
// ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌
// ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄
// ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
// ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀▀▀▀▀▀█░▌
// ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌
// ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▄▄▄▄▄▄▄▄▄█░▌
// ▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░░░░░░░░░░░▌
// ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀
//
// ASCII Art Generated at: http://patorjk.com/software/taag/
//
// Description: Emulates console functions available in
// CodeHS but for use with a NodeJS terminal environment.
//
// Author: Mr. Piltin
//
// Version: 0.1.2
// History:
// 0.1.0: Initial version
// 0.1.1: Remove exports to test global repl.it compatability
// 0.1.2: Restore module.exports to original configuration
//=========================================================
//=========================================================
// Includes
//=========================================================
var read = require("readline-sync"); // Used to process input from terminal
//=========================================================
// Functions
//=========================================================
global.readLine = console.readLine = function (prompt) {
return read.question(prompt);
}
global.readInt = console.readInt = function (prompt) {
while (true) {
var str = read.question(prompt);
var num = parseInt(str);
if (isNaN(num)) {
println("Invalid response, please enter an integer value.");
} else {
return num;
}
}
}
global.readFloat = console.readFloat = function (prompt) {
while (true) {
var str = read.question(prompt);
var num = parseFloat(str);
if (isNaN(num)) {
println("Invalid response, please enter a decimal value.");
} else {
return num;
}
}
}
global.readBoolean = console.readBoolean = function (prompt) {
while (true) {
var str = read.question(prompt);
str = str.toLowerCase();
if (str == "t" || str == "y" || str == "true" || str == "yes") {
return true;
} else if (str == "f" || str == "n" || str == "false" || str == "no") {
return false;
}
println("Invalid response, please enter yes/no or true/false.");
}
}
global.print = console.print = function (text) {
process.stdout.write(text);
}
global.println = console.println = function (text) {
process.stdout.write(text + "\n");
}
global.clearScreen = console.clearScreen = function () {
console.clear();
}
module.exports = {
readLine, readInt, readFloat, readBoolean, print, println, clearScreen
}