From b347e18d9f5171aa70aeae9a1fc20c6df2f7fc05 Mon Sep 17 00:00:00 2001 From: Momozor Date: Wed, 26 May 2021 01:37:18 +0800 Subject: [PATCH] Add randomChoice utility Signed-off-by: Momozor --- Src/Controllers/Admin.js | 7 +++---- Src/Utilities/functions.js | 9 +++++---- tests/unit/utilities/functions.test.js | 4 ++++ 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Src/Controllers/Admin.js b/Src/Controllers/Admin.js index 727c0c9..4a0641a 100644 --- a/Src/Controllers/Admin.js +++ b/Src/Controllers/Admin.js @@ -1,6 +1,5 @@ const APIKEYS = require('../../models/apikeys') - -const uuid = require('../Utilities/functions').uuid +const { uuid } = require('../Utilities/functions') exports.newAPIKEY = async (req, res, next) => { try { @@ -29,7 +28,7 @@ exports.newAPIKEY = async (req, res, next) => { apikey: key }) - res.render('main', { message: 'success', key }) + res.render('main', { message: 'success', key }) } catch (error) { console.log(error) if (error.code === 11000) { @@ -40,4 +39,4 @@ exports.newAPIKEY = async (req, res, next) => { }) } } -} +} diff --git a/Src/Utilities/functions.js b/Src/Utilities/functions.js index d71082e..2a58e05 100644 --- a/Src/Utilities/functions.js +++ b/Src/Utilities/functions.js @@ -1,10 +1,12 @@ const randomNumber = function (length) { return Math.floor(Math.random() * length) } +const randomChoice = function (list) { + return list[randomNumber(list.length)] +} const randomCharacter = function (string) { return string.charAt(randomNumber(string.length)) } - const randomString = function (length, from = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { return Array(length).fill().map(function () { return randomCharacter(from) @@ -13,6 +15,7 @@ const randomString = function (length, from = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg module.exports = { randomNumber, + randomChoice, randomCharacter, randomString, uuid: function () { @@ -85,9 +88,7 @@ module.exports = { sarcasticConverter: function (string) { const possibleOutcomes = ['low', 'high'] const outcome = function () { - return possibleOutcomes[ - randomNumber(possibleOutcomes.length) - ] + return randomChoice(possibleOutcomes) } return string.split('').map(function (character) { diff --git a/tests/unit/utilities/functions.test.js b/tests/unit/utilities/functions.test.js index 58cf535..66a512c 100644 --- a/tests/unit/utilities/functions.test.js +++ b/tests/unit/utilities/functions.test.js @@ -5,6 +5,10 @@ describe('Utility functions', function () { expect(functions.randomNumber(11)) .toBeLessThan(11) }) + it('returns a random object from a list', function () { + expect(functions.randomChoice(['high', 'low', 'medium'])) + .toMatch(/^high|low|medium$/) + }) it('returns a random character from a string', function () { expect(functions.randomCharacter('ABCDE')) .toMatch(/^[A-E]$/)