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
|
const { checkSchema } = require('express-validator/check');
const {
formatResponse,
getRandomArbitrary,
shuffle,
} = require('../utils/common');
exports.validateUnitSchema = checkSchema({
amount: {
in: ['body'],
exists: {
errorMessage: 'Amount cannot be blank!',
},
isInt: {
errorMessage: 'Amount should be an int!',
},
},
});
exports.createUnits = async (req, res) => {
const { amount } = req.body;
// Generates a shuffled units list, for extra randomnization
const availableUnits = shuffle([
'Spearmen',
'Swordsmen',
'Archers',
'Mages',
'Elves',
'Gunmen',
'Spies',
]);
if (availableUnits.length > amount) {
return res
.status(422)
.json(
formatResponse(
false,
`Amount has to be a higher number than the available units. Current available units is ${
availableUnits.length
}`
)
);
}
let amountHelper = amount;
const result = availableUnits
.map((unit, i) => {
// If it is the last available unit, just return the amountHelper value
if (i === availableUnits.length - 1) {
return { [unit]: amountHelper };
}
// Generates a random value using a function with Math.random to generate a random value between two numbers
const value = Math.ceil(
getRandomArbitrary(1, amountHelper - (availableUnits.length - i))
);
amountHelper -= value;
return { [unit]: value };
})
// Reduce the object array to a single object
.reduce(
(obj, item) => {
const currentKey = Object.keys(item)[0];
obj[currentKey] = item[currentKey];
return obj;
},
{ total: amount }
);
return res.status(201).json(formatResponse(true, result));
};
|