Daniel Woelfel Daniel Woelfel - 1 month ago 9
Javascript Question

Generate random numbers from string in JavaScript

I'd like to make a client-side A/B testing library.

Each user has a random number stored in a cookie. Each test has a test name and an array of options. I need a function that picks a random option given the user's random number, the test name, and the options. Of course, the function must always return the same option for a given set of inputs.

How can I write this function in JavaScript?

Answer

My current solution uses the CryptoJS library's MD5 hashing function to generate a random number:

// seed is the user's random number

choose_option = function(seed, test_name, options) {
  word = CryptoJS.MD5("" + seed + test_name).words[0]; // take first 32-bit word
  i = Math.abs(word % options.length);
  return options[i];
}