platform-helpers/utils.js

const path = require('path');
const fse = require('fs-extra');

/**
 * Generic set of utilities class.
 *
 * @static
 * @requires path
 * @requires fs-extra
 * @hideconstructor
 */

class Utils {
  static fileList = [];
  /**
   * Stops processing for the provided amount of time
   * @param {number} milliseconds The amount of time to sleep in milliseconds
   * @example
   * const rootRequire = require('rpcm-root-require');
   * const Utils = ('/platform-helpers/utils');
   *
   * console.log(new Date());
   * // logs: 2022-11-13T14:10:19.500Z
   *
   * const actual = Utils.sleep(5000);
   *
   * console.log(new Date());
   * // logs: 2022-11-13T14:15:19.500Z
   */
  static sleep = async (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
  };

  /**
   * Stops processing for the provided amount of time
   * @param {number} milliseconds The amount of time to wait in milliseconds
   * @example
   * const rootRequire = require('rpcm-root-require');
   * const Utils = ('/platform-helpers/utils');
   *
   * console.log(new Date());
   * // logs: 2022-11-13T14:10:19.500Z
   *
   * const actual = Utils.wait(5000);
   *
   * console.log(new Date());
   * // logs: 2022-11-13T14:15:19.500Z
   */
  static wait = async (milliseconds) => {
    return await this.sleep(milliseconds);
  };

  /**
   * Provides the current timestamp
   * @returns {number} Returns current timestamp
   * @example
   * const rootRequire = require('rpcm-root-require');
   * const Utils = ('/platform-helpers/utils');
   *
   * const actual = Utils.getCurrentTimestamp();
   * console.log(actual);
   * // logs: 123456789
   */
  static getCurrentTimestamp = () => {
    return new Date().getTime();
  };

  /**
   * Provides a random string
   * @returns {string} Returns a random string
   * @example
   * const rootRequire = require('rpcm-root-require');
   * const Utils = ('/platform-helpers/utils');
   *
   * const actual = Utils.getRandomString();
   * console.log(actual);
   * // logs: '123456789'
   */
  static getRandomString = () => {
    return this.getCurrentTimestamp().toString();
  };

  /**
   * Provides a terminal new line (or multiple lines as per argument if provided)
   * @returns {string} Returns a '\n'
   * @example
   * const rootRequire = require('rpcm-root-require');
   * const Utils = ('/platform-helpers/utils');
   * rootRequire('/platform-helpers/string-extensions');
   *
   * const singleNewLine = 'The quick brown {0} jumps {1}{2} the {3} dog!'.format('fox', Utils.getNewLine(), 'over', 'lazy');
   * console.log(singleNewLine);
   * // logs:
   * //   The quick brown fox jumps
   * //   over the lazy dog!
   *
   * const multipleNewLines = 'The quick brown {0} jumps {1}{2} the {3} dog!'.format('fox', Utils.getNewLine(2), 'over', 'lazy');
   * console.log(multipleNewLines);
   * // logs:
   * //   The quick brown fox jumps
   * //
   * //   over the lazy dog!
   */
  static getNewLine = (total) => {
    const newLineChar = '\n';
    total = isNaN(total) ? 1 : total > 0 ? total : 1;
    return total > 1 ? Array.from(Array(total).keys()).reduce((p, c) => p + newLineChar, '') : newLineChar;
  };

  /**
   * Provides a string of repeated characters
   * @param {string} [character=' '] A character to repeat
   * @param {number} [total=1] Number of total expected repetitions
   * @returns {string} Returns a string E.g.: ' '
   * @example
   * const rootRequire = require('rpcm-root-require');
   * const Utils = ('/platform-helpers/utils');
   * rootRequire('/platform-helpers/string-extensions');
   *
   * const singleSpace = 'The quick brown {0} jumps {1}{2} the {3} dog!'.format('fox', Utils.getRepeatedCharacters(), 'over', 'lazy');
   * console.log(singleSpace);
   * // logs: The quick brown fox jumps  over the lazy dog!
   *
   * const multipleSpaces = 'The quick brown {0} jumps {1}{2} the {3} dog!'.format('fox', Utils.getRepeatedCharacters(' ', 4), 'over', 'lazy');
   * console.log(multipleSpaces);
   * // logs: The quick brown fox jumps     over the lazy dog!
   */
  static getRepeatedCharacters = (character, total) => {
    character = character || ' ';
    total = isNaN(total) ? 1 : total > 0 ? total : 1;
    return total > 1 ? Array.from(Array(total).keys()).reduce((p, c) => p + character, '') : character;
  };

  /**
   * Recurse through specified folder and find specific file extensions, return a list
   * @private
   * @param {string} dir the directory to recursively scan
   * @param {array} [extensions=['.json']] a list of file extensions to include in the returned list, like ['.json', '.html']
   * @returns {array} the list of matched files
   */
  static getFilesRecursively = (dir, extensions) => {
    const t = (dir, extensions, payload) => {
      const files = fse.readdirSync(dir);
      payload = payload || [];
      extensions = Array.isArray(extensions) ? extensions : ['.json'];
      files.forEach(file => {
        const filepath = path.join(dir, file);
        const stat = fse.statSync(filepath);

        if (stat.isDirectory()) {
          payload = t(filepath, extensions, payload);
        } else {
          extensions.forEach(function (extension) {
            if (file.indexOf(extension) === file.length - extension.length) {
              payload.push(filepath);
            }
          });
        }
      });
      return payload;
    };
    return t(dir, extensions);
  };
}

module.exports = Utils;