Skip to content
Snippets Groups Projects
helper_functions.js 2.80 KiB

/**
 * Various helper functions to make JavaScript development easier.
 *
 * https://git.brandon-rodriguez.com/javascript/helper_functions
 * Version 1.1
 */

 // System Imports.
 const chalk = require('chalk');
 const readline = require('readline-sync');


/**
 * Update strings to have an equivalent to the "format()" function found in Python strings.
 */
String.prototype.format = function() {
    let i = 0, args = arguments;
    return this.replace(/{}/g, function () {
        return typeof args[i] != 'undefined' ? args[i++] : '';
    });
}


/**
 * Gets human-readible string of current datetime.
 */
function getCurrentDate() {
    let currentDate = new Date;

    return '{}-{}-{} {}:{}:{}'.format(
        ('0000' + currentDate.getFullYear()).slice(-4),
        ('00' + (currentDate.getMonth() + 1)).slice(-2),
        ('00' + currentDate.getDate()).slice(-2),
        ('00' + currentDate.getHours()).slice(-2),
        ('00' + currentDate.getMinutes()).slice(-2),
        ('00' + currentDate.getSeconds()).slice(-2),
    );
}


/**
 * Pauses current execution to prompt user for yes/no input.
 * :return: True on yes response, and False on all other responses.
 */
function userConfirmation() {

    // Get user input.
    try {
        var user_input = readline.question('Is this okay? {}\n'.format(chalk.blue('[ Yes | No ]')));
    } catch (err) {
        // Ignore "timeout" error. Display all others.
        if (err.code != 'ETIMEDOUT') {
            console.log(err);
            throw err;
        }
    }

    // Handle based on user response.
    user_input = user_input.toLowerCase();
    if (user_input == 'yes' || user_input == 'ye' || user_input == 'y') {
        return true;
    } else {
        return false;
    }
}


/**
 * Equivalent of "sleep" in other languages, to delay code for x milliseconds.
 * :param ms: Value in milliseconds to wait (1000 milliseconds = 1 second).
 */
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}


/**
 * Generates a random number between two values.
 * :param min: Inclusive floor for random number. Defaults to 0.
 * :param max: Inclusive ceiling for random number. Defaults to 10 or [ min+1 ], whichever is greater.
 */
function generateRandomNum(min, max) {

    // Validate min.
    if (isNaN(parseInt(min))) {
        // Not a valid number. Default to 0.
        min = 0;
    }

    // Validate max.
    if (isNaN(parseInt(max))) {
        // Not a valid number. Default to 10, or [ min+1 ], whichever is greater.
        max = 10;
        if (max <= min) {
            max = min + 1;
        }
    }

    // Get random number between values (inclusive).
    Math.ceil(min);
    Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1) + min);
}



module.exports = {
    generateRandomNum,
    getCurrentDate,
    sleep,
    userConfirmation,
};