]>
Commit | Line | Data |
---|---|---|
c7b4bd19 BB |
1 | 'use strict'; |
2 | ||
3 | const Fs = require('fs'); | |
4 | const Path = require('path'); | |
5 | ||
fd38d409 RBR |
6 | /** |
7 | * Module containing utility functions | |
8 | * | |
9 | * @name Util | |
10 | * @type Object | |
11 | */ | |
c7b4bd19 BB |
12 | const Util = { |
13 | ||
fd38d409 RBR |
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 | ||
c7b4bd19 BB |
24 | return buffer[0] * 256 + buffer[1]; |
25 | }, | |
26 | ||
fd38d409 RBR |
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 | ||
c7b4bd19 BB |
37 | return array[Math.floor(Math.random() * array.length)]; |
38 | }, | |
39 | ||
fd38d409 RBR |
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 | ||
c7b4bd19 BB |
56 | if (err) { |
57 | return reject(err); | |
58 | } | |
59 | ||
fd38d409 | 60 | const loadedFiles = []; |
c7b4bd19 | 61 | |
fd38d409 RBR |
62 | for (const file of files) { |
63 | const filePath = Path.join(path, file); | |
c7b4bd19 BB |
64 | let loadedFile; |
65 | ||
66 | try { | |
67 | loadedFile = require(filePath); | |
fd38d409 RBR |
68 | } |
69 | catch (err) { | |
c7b4bd19 BB |
70 | return reject(err); |
71 | } | |
72 | ||
73 | loadedFiles.push(loadedFile); | |
74 | } | |
75 | ||
76 | resolve(loadedFiles); | |
77 | }); | |
78 | }); | |
79 | } | |
80 | }; | |
81 | ||
82 | module.exports = Util; |