JSFiddle - React, Tailwind, and code Playground
HTML
<button id="generate" type="button">Generate</button>
<input id="result" />
<button id="validate" type="button">Validate</button>
<span id="isValid"></span>
JavaScript
(function(){
var possible = 'ABCDEFGHJKLMNPQRTUVWXYZ2346789';
function randomString(length) {
var text = '41FD';
for( var i=0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function generateCheckCharacter(input) {
var factor = 2;
var sum = 0;
var n = possible.length;
// Starting from the right and working leftwards is easier since
// the initial "factor" will always be "2"
for (var i = input.length - 1; i >= 0; i--) {
var codePoint = possible.indexOf(input.charAt(i));
var addend = factor * codePoint;
// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;
// Sum the digits of the "addend" as expressed in base "n"
addend = Math.floor(addend / n) + (addend % n);
sum += addend;
}
// Calculate the number that must be added to the "sum"
// to make it divisible by "n"
var remainder = sum % n;
var checkCodePoint = (n - remainder) % n;
return possible.charAt(checkCodePoint);
}
function isValid(input) {
console.log(input);
var factor = 1;
var sum = 0;
var n = possible.length;
// Starting from the right, work leftwards
// Now, the initial "factor" will always be "1"
// since the last character is the check character
for (var i = input.length - 1; i >= 0; i--) {
var codePoint = possible.indexOf(input.charAt(i));
var addend = factor * codePoint;
// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;
// Sum the digits of the "addend" as expressed in base...