JavaScript Pseudo-Random ID Generator

Simple Random Id Generator for JavaScript

Sometimes you might need a Random ID generator. The following generator takes an integer from which it will generate a string of that length. Longer string means more permutations and increased uniqueness. The following function was tested with input 15. A sample space of 5,000,000 IDs was generated and all were tested unique.


function generateRandomId(length) {
    "use strict";
    var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", returnValue = "", x, i;

    for (x = 0; x < length; x += 1) {
        i = Math.floor(Math.random() * 62);
        returnValue += chars.charAt(i);
    }

    return "ID_" + returnValue;
}


NB: Increase length for increased uniqueness




GenerateRandomId Java Permutation Tester
(Simple test for the function above written in java)

import java.util.*;


public class Main {

   
    public static void main(String[] args) {
       
        int perm = 5000000;
        int counter = 0;
       
        //start time
        System.out.println(new Date().toString());
       
        ArrayList <String> str = new ArrayList<String>();
       
       
        for (int i = 0; i < perm; i++) {
            String temp = generateRandomId(15);
            str.add(temp);
        }
       
        System.out.println("done generating IDs");
       
        System.out.println("Checking for uniqueness ....");
       
        for(Object y : GetUniqueValues(str)){
            counter++;
        }
           
        System.out.println("unique " + counter);
        System.out.println(perm==counter);
       
        System.out.println("done ....");
       
        //end time
        System.out.println(new Date().toString());
               
    }
   
   
    public static String generateRandomId(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", returnValue = "";
        int x, i=0;

        for (x = 0; x < length; x += 1) {
            i = (int) Math.floor(Math.random() * 62);
            returnValue += chars.charAt(i);
        }

        return "JS_" + returnValue;
    }
   
    public static ArrayList<String> GetUniqueValues(Collection<String> values)
    {
        return new ArrayList<String>(new HashSet<String>(values));
    }

}

Comments

Popular posts from this blog

JavaScript Module Pattern: 2 Forms

Pseudo-Random UUID Generation with mask support

Mocking Ajax with the JQuery Mockjax Library