summaryrefslogtreecommitdiff
path: root/goodgame/src/controllers/unit.js
diff options
context:
space:
mode:
Diffstat (limited to 'goodgame/src/controllers/unit.js')
-rw-r--r--goodgame/src/controllers/unit.js72
1 files changed, 72 insertions, 0 deletions
diff --git a/goodgame/src/controllers/unit.js b/goodgame/src/controllers/unit.js
new file mode 100644
index 0000000..da162b9
--- /dev/null
+++ b/goodgame/src/controllers/unit.js
@@ -0,0 +1,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));
+};