random code generator javascript


I found this code that generates random alphanumeric codes, I am using it to link 2 types of users, the user can only generate the code once and save it in a table with id and code, then that code is given to other users so that they register it and see some things together.

I want to know how I implement that the codes that are being saved in the bd are not repeated, for the moment I bring them from a database with ajax and they are in an array, the generator has it in a function so that it does not it remains front only is so that they see more or less how it works

       var caracteres = "abcdefghijkmnpqrtuvwxyzABCDEFGHJKMNPQRTUVWXYZ2346789";
       var contraseña = "";
       for (i=0; i<20; i++) contraseña +=caracteres.charAt(Math.floor(Math.random()*caracteres.length)); 
asked by Billy Nieto 22.03.2018 в 18:04

1 answer


Based on a SOen response , what you need to do is a generator that allows you to control the value of the seed , in this way you guarantee that there are no duplicates.

Each time you create your generator with the same seed, you will get the same results over and over again, which will allow you to prove that they are really different.

I recommend reading about yield to avoid calling from the start the generator and continue where the previous value was generated, but that will depend on the stack you are driving.

function RNG(seed) {
  // constantes de GCC
  this.m = 0x80000000; // 2**31;
  this.a = 1103515245;
  this.c = 12345;

  this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));
RNG.prototype.nextInt = function() {
  this.state = (this.a * this.state + this.c) % this.m;
  return this.state;
RNG.prototype.nextFloat = function() {
  // en el rango [0,1]
  return this.nextInt() / (this.m - 1);
RNG.prototype.nextRange = function(start, end) {
  // en el rango [inicio, fin)
  var rangeSize = end - start;
  var randomUnder1 = this.nextInt() / this.m;
  return start + Math.floor(randomUnder1 * rangeSize);
RNG.prototype.choice = function(array) {
  return array[this.nextRange(0, array.length)];

var contraseñas = [];

var rng = new RNG(20);
var caracteres = "abcdefghijkmnpqrtuvwxyzABCDEFGHJKMNPQRTUVWXYZ2346789".split('');
for (var w = 0; w < 330; w++) {
  var contraseña = "";
  for (var i = 0; i < 30; i++) {
    contraseña += rng.choice(caracteres);
answered by 22.03.2018 / 21:00