Generate an OTP
MediumStrings10 min
Write a function generateOtp(random) that returns a random one-time password in the format of 'A23DR': one capital letter, two digits, then two capital letters.
- The result is a string of 5 characters: a capital Latin letter from
AtoZ, two digits from0to9, two capital letters. - The parameter
randomis a function that returns a number from 0 up to, but not including, 1, like Math.random(). Ifrandomis not given, useMath.random:function generateOtp(random = Math.random). - Call
random()exactly once for every character, from left to right, so 5 times in total. - For a letter take
ALPHABET[Math.floor(random() * 26)], whereALPHABETis'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. For a digit takeMath.floor(random() * 10). Math.floor cuts off the fraction. - So
generateOtp(() => 0)returns'A00AA', andgenerateOtp(() => 0.999)returns'Z99ZZ'.
Why a parameter: a test cannot know a random result in advance. With its own random, the test knows the exact answer. Without an argument the function stays random.
Examples
generateOtp(() => 0)Returns 'A00AA'
generateOtp(() => 0.5)Returns 'N55NN'
Asked at Luxoft · Source
Loading the editor...
- random() always 0 gives A00AA
- A sequence of numbers gives A23DR
- Without an argument: 200 calls match the format and are not all the same
Hidden tests run on Submit