-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.js
98 lines (77 loc) · 2.58 KB
/
helper.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
export function randomNumber(min = 0, max = 100) {
return Math.round((max - min) * Math.random()) + min;
}
export function randomValue(types, maxDepth = 2) {
let depth = 0;
let allTypes = ['string', 'number', 'boolean', 'null', 'undefined', 'array', 'object'];
let type;
if (types) {
types = Array.isArray(types) ? types : [types]
} else {
types = allTypes;
}
type = randomNumber(0, types.length - 1);
switch (types[type]) {
case 'string': {
let length = randomNumber(3, 10);
let string = [];
for (let i = 0; i < length; i++) {
string.push(String.fromCharCode(randomNumber(33, 126)));
}
return string.join('');
}
case 'number':
return randomNumber();
case 'boolean':
return !!randomNumber(0, 1);
case 'null':
return null;
case 'array': {
if (depth < maxDepth) {
let length = randomNumber(3, 10);
let array = [];
depth++;
for (let i = 0; i < length; i++) {
array.push(randomValue(depth == maxDepth ? allTypes.slice(0, -2) : allTypes, maxDepth - depth));
}
return array;
} else {
return randomValue(allTypes.slice(0, -2));
}
}
case 'object': {
if (depth < maxDepth) {
let length = randomNumber(3, 10);
let object = {};
depth++;
for (let i = 0; i < length; i++) {
let key = randomValue('string');
object[key] = randomValue(depth == maxDepth ? allTypes.slice(0, -2) : allTypes, maxDepth - depth);
}
return object;
} else {
return randomValue(allTypes.slice(0, -2));
}
}
}
}
export function randomNumberArray(mode, minLength = 3, maxLength = 10, min, max) {
let length = randomNumber(minLength, maxLength);
let array = [];
for (let i = 0; i < length; i++) {
let number = randomNumber(min, max);
if ((mode == 'even' && number % 2) || (mode == 'odd' && !(number % 2))) {
number++;
}
array.push(number);
}
return array;
}
export function randomStringArray(minLength = 3, maxLength = 10) {
let length = randomNumber(minLength, maxLength);
let array = [];
for (let i = 0; i < length; i++) {
array.push(randomValue('string'));
}
return array;
}