JSFiddle - React, Tailwind, and code Playground

by Vladimir Sobolev

JavaScript

var items = [ 
				{"name": "item1", "weight":1},
				{"name": "item2", "weight":2},
				{"name": "item3", "weight":4},
				{"name": "item4", "weight":8},
				{"name": "item5", "weight":16}
			 ], test = [0,0,0,0,0];


			function getWrnd(items) {
				var total = current = 0, rnd;
				for (var i in items) total += items[i].weight;
				rnd = Math.floor(Math.random() * total);
			 	for (var i in items) if (rnd < (current += items[i].weight)) { test[i]++; return items[i];}
			}
			
			// TEST

			for (var i = 0;i < 100000; i++) {
				getWrnd(items);
			}
			
			document.body.innerHTML = Math.round(test[0]/test[0]) + ' ' +Math.round(test[1]/test[0]) + ' ' +Math.round(test[2]/test[0]) + ' ' +Math.round(test[3]/test[0]) + ' ' + Math.round(test[4]/test[0]);