]> git.r.bdr.sh - rbdr/tomato-sauce/blame - lib/util.js
Add new port
[rbdr/tomato-sauce] / lib / util.js
CommitLineData
c7b4bd19
BB
1'use strict';
2
3const Fs = require('fs');
4const Path = require('path');
5
fd38d409
RBR
6/**
7 * Module containing utility functions
8 *
9 * @name Util
10 * @type Object
11 */
c7b4bd19
BB
12const Util = {
13
a0666be3 14 /**
fd38d409
RBR
15 * Parses a 16 bit number buffer
16 *
17 * @function parse16BitBuffer
18 * @memberof Util
19 * @param {Array<String>} buffer the buffer to parse
20 * @return {Number} the parsed value
21 */
a0666be3 22 parse16BitBuffer(buffer) {
fd38d409 23
a0666be3
RBR
24 return buffer[0] * 256 + buffer[1];
25 },
c7b4bd19 26
a0666be3 27 /**
fd38d409
RBR
28 * Picks a random element from an array
29 *
30 * @function pickRandom
31 * @memberof Util
32 * @param {Array} array the array to use
33 * @return {Any} the picked element
34 */
a0666be3 35 pickRandom(array) {
fd38d409 36
a0666be3
RBR
37 return array[Math.floor(Math.random() * array.length)];
38 },
c7b4bd19 39
a0666be3 40 /**
fd38d409
RBR
41 * For a gi ven path, requires all of the files and returns an array
42 * with the results. If the directory contains any non-requireable
43 * files, it will fail.
44 *
45 * @function loadFiles
46 * @memberof Util
47 * @param {String} path the path where the files are located
48 * @return {Array} the array of all the loaded modules
49 */
a0666be3 50 loadFiles(path) {
fd38d409 51
a0666be3 52 return new Promise((resolve, reject) => {
fd38d409 53
a0666be3 54 Fs.readdir(path, (err, files) => {
fd38d409 55
a0666be3
RBR
56 if (err) {
57 return reject(err);
58 }
c7b4bd19 59
a0666be3 60 const loadedFiles = [];
c7b4bd19 61
a0666be3
RBR
62 for (const file of files) {
63 const filePath = Path.join(path, file);
64 let loadedFile;
c7b4bd19 65
a0666be3
RBR
66 try {
67 loadedFile = require(filePath);
68 }
69 catch (err) {
70 return reject(err);
71 }
c7b4bd19 72
a0666be3
RBR
73 loadedFiles.push(loadedFile);
74 }
c7b4bd19 75
a0666be3
RBR
76 resolve(loadedFiles);
77 });
78 });
79 }
c7b4bd19
BB
80};
81
82module.exports = Util;