3

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Daniel Woelfel
  • 518
  • 5
  • 13

3 Answers3

5

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];
}
Daniel Woelfel
  • 518
  • 5
  • 13
  • This sounds perfect given your requirements - do you have any particular objection to this technique, or are you just curious if there's anything else out there? – Bubbles Dec 20 '12 at 03:18
  • @Bubbles I'm hoping that there is something simpler, which doesn't require a dependency on an external library. I'm also worried that I've introduced some statistical bias or dependence between tests. – Daniel Woelfel Dec 20 '12 at 05:55
  • It's also possible to generate the numbers in a specific range. See here: http://stackoverflow.com/questions/15034013/generate-a-number-in-a-specific-range-from-a-checksum – Anderson Green Feb 23 '13 at 00:45
1

Maybe a bit later and a bit exagerate as the lib in question has many feature you may not use, but I always have this included in my projects so let me expose my solution to the very same problem you had. This lib can be initalized with a seed (chancejs#seed), very useful for creating repeatable results:

const Chance = require('chance');
c1 = Chance('email@gmail.com', 'maybe a uuid here');
c1.integer();
c1.natural({min:1000,max:9999});

c2 = Chance('foo-baz-bar');
c2.string();
c2.word();
...

hope this helps.

Daniele Vrut
  • 2,835
  • 2
  • 22
  • 32
0
var availNum= [1, 4, 5, 6, 7, 8, 12];
//@var count number of random num you want 
function createRandomData(count) {
    var data = [],
    for (var i = 0; i < count; i++) {
        var random = availNum[Math.floor(Math.random() * availNum.length)],

        data.push({
          random:random 
        });
    }
    return data;
}
Arun Killu
  • 13,581
  • 5
  • 34
  • 61