]> git.r.bdr.sh - rbdr/tomato-sauce/blob - lib/util.js
Add new port
[rbdr/tomato-sauce] / lib / util.js
1 'use strict';
2
3 const Fs = require('fs');
4 const Path = require('path');
5
6 /**
7 * Module containing utility functions
8 *
9 * @name Util
10 * @type Object
11 */
12 const Util = {
13
14 /**
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 */
22 parse16BitBuffer(buffer) {
23
24 return buffer[0] * 256 + buffer[1];
25 },
26
27 /**
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 */
35 pickRandom(array) {
36
37 return array[Math.floor(Math.random() * array.length)];
38 },
39
40 /**
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 */
50 loadFiles(path) {
51
52 return new Promise((resolve, reject) => {
53
54 Fs.readdir(path, (err, files) => {
55
56 if (err) {
57 return reject(err);
58 }
59
60 const loadedFiles = [];
61
62 for (const file of files) {
63 const filePath = Path.join(path, file);
64 let loadedFile;
65
66 try {
67 loadedFile = require(filePath);
68 }
69 catch (err) {
70 return reject(err);
71 }
72
73 loadedFiles.push(loadedFile);
74 }
75
76 resolve(loadedFiles);
77 });
78 });
79 }
80 };
81
82 module.exports = Util;