]> git.r.bdr.sh - rbdr/tomato-sauce/blob - lib/util.js
3234d3edbe6aa7641005db82912a023a1408a023
[rbdr/tomato-sauce] / lib / util.js
1 'use strict';
2
3 const Fs = require('fs');
4 const Path = require('path');
5
6 // Module containing utility functions.
7 const Util = {
8
9 // Parses a 16 bit number buffer.
10 parse16BitBuffer: function (buffer) {
11 return buffer[0] * 256 + buffer[1];
12 },
13
14 // Picks a random element from an array.
15 pickRandom: function (array) {
16 return array[Math.floor(Math.random() * array.length)];
17 },
18
19 // For a given path, requires all of the files and returns an array
20 // with the results. If the directory contains any non-requireable file,
21 // it will fail.
22 loadFiles: function (path) {
23 return new Promise(function (resolve, reject) {
24 Fs.readdir(path, function (err, files) {
25 if (err) {
26 return reject(err);
27 }
28
29 let loadedFiles = [];
30
31 for (let file of files) {
32 let filePath = Path.join(path, file);
33 let loadedFile;
34
35 try {
36 loadedFile = require(filePath);
37 } catch (err) {
38 return reject(err);
39 }
40
41 loadedFiles.push(loadedFile);
42 }
43
44 resolve(loadedFiles);
45 });
46 });
47 }
48 };
49
50 module.exports = Util;