Pick from choices

Benchmark created by Vesa Piittinen on


Description

CSS-Tricks: Choose a Random Option based on a Range

Setup

var choices = [
      [10, "apples"],
      [20, "oranges"],
      [70, "bananas"] 
    ];
    
    var pickInt32Array=(function(){var r=new Int32Array(2),o;return function pick(c){r[0]=Math.random()*100;for(r[1]=-1;(o=c[++r[1]])&&r[0]>=o[0];r[0]-=o[0]);if(o)return o[1]}})()

Test runner

Ready to run.

Testing in
TestOps/sec
imma
// 81 chars
(function pick(c){var r=Math.random()*100,n;for(n of c)if(r-=n[0],r<0)return n[1]})(choices)
ready
imma in integer
// 85 chars
(function pick(c){var r=~~(Math.random()*100),n;for(n of c)if(r-=n[0],r<0)return n[1]})(choices)
ready
Merri
// 94 chars; much faster, but the input array first item value total MUST equal 100
(function pick(c){for(var i=-1,j,r=~~(Math.random()*100);r>=(j=c[++i][0]);r-=j);return c[i][1]})(choices)
ready
Merri + safety
// 102 chars
(function pick(c){for(var i=-1,o,r=~~(Math.random()*100);(o=c[++i])&&r>=o[0];r-=o[0]);if(o)return o[1]})(choices)
ready
Merri + Int32Array
// 160+ chars
pickInt32Array(choices)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.