Generate random numbers from string in JavaScript

天涯浪子 提交于 2019-12-06 11:35:24

问题


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?


回答1:


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



回答2:


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:


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


来源:https://stackoverflow.com/questions/13964762/generate-random-numbers-from-string-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!