Generate random numbers from string in JavaScript

2019-04-12 18:55发布

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?

3条回答
ゆ 、 Hurt°
2楼-- · 2019-04-12 19:30

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.

查看更多
干净又极端
3楼-- · 2019-04-12 19:39

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];
}
查看更多
太酷不给撩
4楼-- · 2019-04-12 19:41
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;
}
查看更多
登录 后发表回答