aboutsummaryrefslogtreecommitdiff
path: root/lib/util.js
blob: 4c8c3c11012710e963fac3a106c25b0a730a39ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';

const Fs = require('fs');
const Path = require('path');

/**
 * Module containing utility functions
 *
 * @name Util
 * @type Object
 */
const Util = {

    /**
   * Parses a 16 bit number buffer
   *
   * @function parse16BitBuffer
   * @memberof Util
   * @param {Array<String>} buffer the buffer to parse
   * @return {Number} the parsed value
   */
    parse16BitBuffer(buffer) {

        return buffer[0] * 256 + buffer[1];
    },

    /**
   * Picks a random element from an array
   *
   * @function pickRandom
   * @memberof Util
   * @param {Array} array the array to use
   * @return {Any} the picked element
   */
    pickRandom(array) {

        return array[Math.floor(Math.random() * array.length)];
    },

    /**
   * For a gi ven path, requires all of the files and returns an array
   * with the results. If the directory contains any non-requireable
   * files, it will fail.
   *
   * @function loadFiles
   * @memberof Util
   * @param {String} path the path where the files are located
   * @return {Array} the array of all the loaded modules
   */
    loadFiles(path) {

        return new Promise((resolve, reject) => {

            Fs.readdir(path, (err, files) => {

                if (err) {
                    return reject(err);
                }

                const loadedFiles = [];

                for (const file of files) {
                    const filePath = Path.join(path, file);
                    let loadedFile;

                    try {
                        loadedFile = require(filePath);
                    }
                    catch (err) {
                        return reject(err);
                    }

                    loadedFiles.push(loadedFile);
                }

                resolve(loadedFiles);
            });
        });
    }
};

module.exports = Util;