Skip to content

Commit

Permalink
Add randomChoice utility
Browse files Browse the repository at this point in the history
Signed-off-by: Momozor <[email protected]>
  • Loading branch information
Momozor committed May 25, 2021
1 parent 2fd5e7e commit b347e18
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 8 deletions.
7 changes: 3 additions & 4 deletions Src/Controllers/Admin.js
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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) {
Expand All @@ -40,4 +39,4 @@ exports.newAPIKEY = async (req, res, next) => {
})
}
}
}
}
9 changes: 5 additions & 4 deletions Src/Utilities/functions.js
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -13,6 +15,7 @@ const randomString = function (length, from = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg

module.exports = {
randomNumber,
randomChoice,
randomCharacter,
randomString,
uuid: function () {
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions tests/unit/utilities/functions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]$/)
Expand Down

0 comments on commit b347e18

Please sign in to comment.