The setup:
I am using _.sample()
for my first time in some client's code and I wanted to test it to make sure that it produced an even distribution of samples time after time.
To test this, I created the following code:
(function(arraySize, timesToRun){
arraySize = arraySize || 10;
timesToRun = timesToRun || 1000;
let myArray = Array.apply(null, {length: arraySize}).map(Number.call, Number);
let resultsArray = Array.apply(null, Array(arraySize)).map(Number.prototype.valueOf,0);
for (let i = 0; i < timesToRun; i++) {
var result = _.sample(myArray);
resultsArray[result]++;
}
return resultsArray;
})(10, 1000);
This runs perfectly in my Chrome browser to give me the following result:
[93, 112, 97, 87, 97, 107, 97, 104, 105, 101]
As expected, with other inputs (20, 10000)
we get:
[646, 663, 641, 749, 648, 686, 642, 631, 663, 688, 691, 639, 672, 663, 678]
So... That's it, the code does what it needs for me, completely acceptable.
Here is what I'm looking for:
Explanation for the following:
An answer will be accepted if it can answer any/all of these three questions.
- I do not understand how
Array.apply(null, {length: arraySize}).map(Number.call, Number);
is working. Specifically the part that is VERY confusing to me is what is happening in the map
call: map(Number.call, Number)
- Why does this produce an array that looks like [0,1,2,3,4,5,6,7,8,9]
? Seeing as this question is getting sliced up into separate?questions, I've asked this specific question elsewhere
- Why do we need
Number.prototype.valueOf
in map(Number.prototype.valueOf,0)
I farmed this question out to a new post this has been answered here
- Is there a better way to set default values to
arraySize
and timesToRun
? (Note: I'm putting the same value in the function call just for convince - I know this is not required.)
Please make any other critiques to the code, I'm asking this question to learn more about Javascript and to see if there are any obvious improvements which could be made to this function.
Wish List:
Perhaps anyone could comment if they know a good way to do this:
I'd like to find a neat clean way to create graphical output for this test. Does anyone know an easy library to use so that I can graph this. Maybe for more input we could get a nice bell curve? - Here is a simple way - I'm putting this here inline because again, this question has been downvoted, but I wanted to give the information for anyone else looking to do this.
Important Note!
This question was formatted improperly. I will split this question up into smaller questions and post them separately. I've made this edit after reading: https://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/
... Well, I can't close this question - so I'll leave the original post below. If anyone decides to answer this, I'm still looking for the answer to these questions and I will accept.
See Question&Answers more detail:
os