UNPKG

ccc_utils

Version:

A Library with useful Methods for the Coding Contest

134 lines (109 loc) 3.07 kB
const fs = require("fs"); const readline = require("readline"); 'use strict'; /** * Read in File Synchronously * @param {string} file * @return {array} */ module.exports.readFileSync = function (file) { return fs.readFileSync(file); } /** * Read in Lines from File Asynchronously and return a Array with the Lines as String * @param {string} file * @param {function} callback * @return {array} */ module.exports.readFileLines = function (file, callback) { let lines = []; const rl = readline.createInterface({ input: fs.createReadStream(file) }) rl.on("line", function (line) { lines.push(line); }); rl.on("close", function (line) { callback(lines); }) } /** * Read in Lines from File Asynchronously and return a Array with the Lines as Numbers * @param {string} file * @param {function} callback * @return {array} */ module.exports.readFileLinesAsNumber = function (file, cb) { let lines = []; const rl = readline.createInterface({ input: fs.createReadStream(file) }) rl.on("line", function (line) { lines.push(+line); }); rl.on("close", function (line) { cb(lines); }) } /** * Read in Numbers seperated by whitespaces from File Asynchronously and return a Array with the Lines as Numbers * @param {string} file * @param {function} callback * @return {array} */ module.exports.readFileNumbersWhitespaced = function (file, lineC, callback) { let numbers = []; let lineCount = 0; const rl = readline.createInterface({ input: fs.createReadStream(file) }) rl.on("line", function (line) { if(lineCount == lineC){ numbers = line.split(" "); for(i = 0; i < numbers.length; i++){ numbers[i] = +numbers[i]; } } lineCount++; }); rl.on("close", function (line) { callback(numbers); }) } /** * Read in String from Console and return the Input * @return {string} */ module.exports.readInFromConsole = function () { const stdin = process.openStdin(); stdin.addListener("data", function (d) { return d.toString().trim(); }); } /** * Read a Number from Console and return the Input * @return {number} */ module.exports.readInNumberFromConsole = function () { const stdin = process.openStdin(); stdin.addListener("data", function (d) { return +d.toString().trim(); }); } /** * Read in Numbers from Console and return the Input as Array * @return {array} */ module.exports.readInNumbersFromConsole = function (callback) { const stdin = process.openStdin(); let numbers = []; stdin.addListener("data", function (d) { let input = d.toString().trim(); if (!isNaN(input)) { numbers.push(+input); }else{ callback(numbers); process.exit(0); } }); }