JSFiddle - React, Tailwind, and code Playground
HTML
<div class="exclusions">
<p>Excluded Serial numbers that will never be generated:</p>
<div>
<input type="text" class="test" name="test[]" value="A-B-C" />
</div>
<div>
<input type="text" class="test" name="test[]" value="B-A-C" />
</div>
<div>
<input type="text" class="test" name="test[]" value="C-A-C" />
</div>
</div>
<div class="output-wrapper">
<p>Generated Serials Below:</p>
<div class="output">
</div>
</div>
CSS
.test {
display: block;
margin: 10px auto;
width: 50%;
padding: 5px;
}
.exclusions {
border: 1px solid red;
background-color: lightgray;
padding: 0 15px;
text-align: center;
}
.output-wrapper {
margin: 15px 0;
padding: 0 15px;
border: 1px solid green;
box-sizing: border-box;
}
.output-wrapper > p {
text-align: center;
padding: 10px;
border-top: 1px dashed black;
border-bottom: 1px dashed black;
}
.output {
display: block;
margin: 0 auto;
text-align: center;
}
.inline-block {
display: inline-block;
padding: 0 15px;
box-sizing: border-box;
}
JavaScript
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
else
return string + this;
};
jQuery(document).ready(function($) {
$.extend({
generateSerial: function(formula, chrs, checks) {
var formula = formula && formula != "" ? formula : 'XXX-XXX-XXX-XXX-XXX', // Default Formula to use, should change to what's most commonly used!
chrs = chrs && chrs != "" ? chrs : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", // Default characters to randomize, if not defined!
serial = "",
len = (formula.match(/X/g) || []).length,
indices = [],
rand;
// Get all "-" char indexes
for(var i=0; i < formula.length; i++) {
if (formula[i] === "-") indices.push(i);
}
do {
rand = Array(len).join().split(',').map(function() {
return chrs.charAt(Math.floor(Math.random() * chrs.length));
}).join('');
// Rebuild string!
if (indices.length > 0)
{
for(var x=0; x < indices.length; x++)
rand = rand.insert(indices[x], '-');
}
} while (checks && $.inArray(rand, checks) !== -1);
return rand;
}
});
if ($(".test").length)
var elem = $(".test").map(function() {return $(this).val(); }).get();
else
var elem = [];
for (var x = 0; x < 16; x++)
{
var output = $.generateSerial('X-X-X', 'ABC', elem);
console.log(output);
elem.push(output);
var p = $("<p />").text(output);
if ((x % 4) == 0 || x == 0) {
var div = $("<div />").addClass("inline-block");
div.appendTo($(".output"));
}
p.appendTo(div);
}
});