Generate random numbers from string in JavaScript - Stack Overflow

I'd like to make a client-side AB testing library.Each user has a random number stored in a cooki

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?

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?

Share Improve this question edited Jan 7, 2014 at 13:48 BenMorel 36.7k51 gold badges205 silver badges336 bronze badges asked Dec 20, 2012 at 3:15 Daniel WoelfelDaniel Woelfel 5165 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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];
}

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 protected]', 'maybe a uuid here');
c1.integer();
c1.natural({min:1000,max:9999});

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

hope this helps.

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;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742335284a4424527.html

相关推荐

  • Generate random numbers from string in JavaScript - Stack Overflow

    I'd like to make a client-side AB testing library.Each user has a random number stored in a cooki

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信