Code Lab

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 A to Z, two digits from 0 to 9, two capital letters.
  • The parameter random is a function that returns a number from 0 up to, but not including, 1, like Math.random(). If random is not given, use Math.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)], where ALPHABET is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. For a digit take Math.floor(random() * 10). Math.floor cuts off the fraction.
  • So generateOtp(() => 0) returns 'A00AA', and generateOtp(() => 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'

`Math.floor(0.5 * 26)` is 13, the letter N. `Math.floor(0.5 * 10)` is 5.

Asked at Luxoft · Source

Loading the editor...
  1. random() always 0 gives A00AA
  2. A sequence of numbers gives A23DR
  3. Without an argument: 200 calls match the format and are not all the same

Hidden tests run on Submit.