-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobals.js
108 lines (93 loc) · 2.46 KB
/
globals.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
global.join = require("path").join;
global.__basedir = __dirname;
global.__libdir = join(__dirname, "lib");
global.__webdir = join(__dirname, "web");
global.__datadir = join(__dirname, "data");
/**
* Synchronously iterate through modules in a directory and require them
* @param {String} dir The target module directory
* @param {Number} [recursive=Infinity] The depth of the index, recurse into directories
* @param {Array} [args=[]] Optional args to pass into any resulting class constructors
* @return {Object} An object of the aggregated modules
*/
global.index = function(dir, recursive = Infinity, ...args)
{
const fs = require("fs")
, files = fs.readdirSync(dir)
, modules = {};
if ((typeof recursive) !== "number")
{
args = [ recursive ].concat(args);
recursive = Infinity;
}
for (const file of files)
{
if (file === "index.js")
continue;
const filePath = join(dir, file)
, stat = fs.statSync(filePath);
if (stat.isDirectory())
{
// 'recursive' here stands for the the amount of dirs we should travel and is controlled by decreasing with every directory call
if (recursive === 0)
continue;
modules[file] = global.index(filePath, recursive - 1, ...args);
continue;
}
if (args.length)
modules[file.replace(".js", "")] = new (require(filePath))(...args);
else
modules[file.replace(".js", "")] = require(filePath);
}
return modules;
};
/**
* Returns a title case representation of the object.
* @return {String} Title case representation of the object.
*/
String.prototype.toTitleCase = function()
{
return this.replace(
/\w\S*/g,
txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
);
};
/**
* Get the first element of this array.
* @return {*}
*/
Array.prototype.first = function()
{
return this[0];
};
/**
* Get the last element of this array.
* @return {*}
*/
Array.prototype.last = function()
{
return this[this.length - 1];
};
/**
* Get a pseudo-random element. See https://v8.dev/blog/math-random
* @return {*}
*/
Array.prototype.random = function()
{
return this[Math.floor(Math.random() * this.length)];
};
/**
* Shuffle the array. This does not mutate the original array.
* @return {Array} The shuffled array copy.
*/
Array.prototype.shuffle = function()
{
let copy = Array.assign([], this);
// https://stackoverflow.com/a/12646864
for (let i = copy.length - 1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
};