JSFiddle - React, Tailwind, and code Playground
HTML
<span id="test"></span><br/>
<input type="button" id="generate" value="Generate again"><br/><br/>
History: <div id="history"></div>
Unique numbers left: <span id="numLeft"></span>
JavaScript
var UniqueRandom = {
NumHistory: [],
generate: function (maxNum, id) {
var hardCap = 100; // hard limiting, to prevent function going haywire
if (!this.NumHistory[id]) this.NumHistory[id] = [];
if (maxNum >= 1) {
var current = Math.round(Math.random() * (maxNum - 1)), x = 0;
if (maxNum > 1 && this.NumHistory[id].length > 0) {
if (this.NumHistory[id].length !== maxNum) {
while ($.inArray(current, this.NumHistory[id]) !== -1 || x < hardCap) {
current = Math.round(Math.random() * (maxNum - 1));
x = x + 1;
}
this.NumHistory[id].push(current);
} else {
//reset
this.NumHistory[id] = [current];
}
} else {
//first time only
this.NumHistory[id].push(current);
}
return current;
} else {
return maxNum;
}
},
clear: function (id) {
this.NumHistory[id] = [];
}
};
$(document).ready(function () {
var range = 100;
$('#generate').click(function(){
$('#test').html(UniqueRandom.generate(range , 'test'));
$('#history').html('');
$.each(UniqueRandom.NumHistory['test'], function(key, value){
$('#history').append(value+', ');
});
$('#numLeft').html(range -UniqueRandom.NumHistory['test'].length);
});
$('#generate').click();
});