JavaScript/Groovy/PHP - Id Generator

kevinhng86

Member
Registered
Joined
Jan 12, 2017
Messages
58
Points
0
Hello all,

This is a function that I wrote in both Groovy and JavaScript that generate random Id number. This is one of the really great script, it show how you can deal with generate a random text string, and by having it in both version, it show an example of how you can port your source code into difference scripting format.

Both version of this script will do exactly the same thing, it is just whether which language you would prefer to use. The concept is that you have a string of alphabet from a-z and then 0-9 to generate a random value from. Each character in this string have a position. Therefore you generate a random number with the minimum is 0 and maximum is the max length of the string. You use this number to get a single alphabet character. For every random alphabet letter needed you just have to put it in an array and later turn that array back into a string, and you would have a string full of random alphabet letter or number. This is depend on what you would like to generate.

So what does this code do? It will take in four value, the first 3 value is the none random id number that you would like it to have. Each value is for a block of none random number. None of which can have negative. The fourth value is the length of each id block. This will be fill in with 0 to make up the complete block where your Id number is not large enough to fill the length. The minimum length is 2. If no length is given the script default value is 5. You can skip out the second and third value block simply passing it a 0 value or an empty string.

An example output would be like this idGenerator(1,0,0,5) would produce xxxxx-00001 -> in this example where xxxxx will be five random characters.
idGenerator(1,3,10,4) would produce xxxx-0001-xxxx-0003-xxxx-0010 -> in this example where x are will be replace with a random character.

This script is great for producing very secure user Id where one user cannot guess another but still give you the advantage where an admin can associate which Id belong to which group of user or department.

This code below is the JavaScript version:
Code:
// This is the JavaScript version.
function idGenerator(n1, n2, n3, lead0){
            function getRandom(min, max) {
 				 return Math.random() * (max - min) + min;
			}
            
            Number.prototype.pad = function(size) {
     		 var s = String(this);
      		while (s.length < (size || 1)) {s = "0" + s;}
      		return s;
    		}
            
            if (typeof(n1) === 'undefined') n1 = 1;
            if (typeof(n2) === 'undefined') n2 = 0 ;
            if (typeof(n3) === 'undefined') n3 = 0 ;
            if (typeof(lead0) === 'undefined') lead0 = 5;
            
            
            if (n1 < 0 || n2 < 0 || n3 < 0 || lead0 < 0){var error = "can't work with negative"; return error;};
            if (n2 < 1 && n3 > 0){var error = "input have to follow order" ; return error;};
            if (lead0 < 2){var error="need at least 2"; return error;};
            var n1 = n1 === 0? 1 : n1;
            var alpha = "abcdefghijklmnopqrstuvwxyz123456789";
            var idstr = "";
            n1out = (n1).pad(lead0); n2out = (n2).pad(lead0); n3out = (n3).pad(lead0);
            rdblk = 0;
            rdarr = [];

            if (n1 > 0){rdblk = rdblk +1};   if (n2 > 0){rdblk = rdblk +1}; if (n3 > 0){rdblk = rdblk +1};

            for (i = 0; i < rdblk; i++) {
            var a = 0;
            var b = "";
            while (a < lead0){
            b += alpha.charAt(getRandom(0, alpha.length) );
            a++;
            }
            rdarr[i] = b;
            }

            if (rdblk == 3){idstr = rdarr[0]+ "-" +n1out+ "-" +rdarr[1]+ "-" +n2out+ "-" +rdarr[2]+ "-"+n3out};
            if (rdblk == 2){idstr = rdarr[0]+ "-" +n1out+ "-" +rdarr[1]+ "-" +n2out};
            if (rdblk == 1){idstr = rdarr[0]+ "-" +n1out};


            return idstr;
        }
This code below is the Groovy version:
Code:
// Groovy version
​public idGenerator(int n1 = 0, int n2 = 0, int n3 = 0, int lead0 = 5){
    if (n1 < 0 || n2 < 0 || n3 < 0 || lead0 < 0){return "can't work with negative"}
    if (n2 < 1 &&  n3 > 0){return "input have to follow order"}
    if (lead0 < 2){return "need at least 2"}
    n1 = (n1 == 0)? 1 : n1 
    format = "%0"+lead0+"d"
    String alpha = "abcdefghijklmnopqrstuvwxyz123456789"
    String idstr
    n1out = String.format(format, n1); n2out = String.format(format, n2); n3out = String.format(format, n3)
    rdblk = 0
    rdarr = []
    
    if (n1 > 0){rdblk = rdblk +1};   if (n2 > 0){rdblk = rdblk +1}; if (n3 > 0){rdblk = rdblk +1}
    
    for (i = 0; i < rdblk; i++) { 
    rdarr[i] = new Random().with { (1..lead0).collect { alpha[nextInt( alpha.length() ) ] }.join()}
    }
    
    if (rdblk == 3){idstr = rdarr[0]+ "-" +n1out+ "-" +rdarr[1]+ "-" +n2out+ "-" +rdarr[2]+ "-"+n3out}
    if (rdblk == 2){idstr = rdarr[0]+ "-" +n1out+ "-" +rdarr[1]+ "-" +n2out}
    if (rdblk == 1){idstr = rdarr[0]+ "-" +n1out}
    

    return idstr
}

The below is the PHP version:
Code:
<?php
function idGenerator($n1 = 0, $n2 = 0, $n3 = 0, $lead0 = 5){
    if ($n1 < 0 || $n2 < 0 || $n3 < 0 || $lead0 < 0){ return "can't work with negative";}
    if ($n2 < 1 && $n3 > 0){return "input have to follow order";}
    if ($lead0 < 2){return "need at least 2";}
    $n1 = ($n1 == 0)? 1 : $n1; 
    $format = "%'.0".$lead0."d";
    $alpha = "abcdefghijklmnopqrstuvwxyz123456789";
    $idstr; 
    $n1out = sprintf($format, $n1); $n2out = sprintf($format, $n2); $n3out = sprintf($format, $n3);
    $rdblk = 0;
    $rdarr = array();
    
    if ($n1 > 0){$rdblk = $rdblk +1 ;};  if ($n2 > 0){$rdblk = $rdblk +1;}; if ($n3 > 0){$rdblk = $rdblk +1 ;};
    $rdstr = "";
    for ($i = 0; $i < $rdblk; $i++) { 
        for ($id = 0; $id < $lead0; $id++){
            $rdstr = $rdstr . $alpha[rand(0,strlen($alpha)-1)];
        } 
    $rdarr[$i] = $rdstr; $rdstr = "";
    }
    
    if ($rdblk == 3){$idstr = $rdarr[0]. "-" .$n1out. "-" .$rdarr[1]. "-" .$n2out. "-" .$rdarr[2]. "-".$n3out;};
    if ($rdblk == 2){$idstr = $rdarr[0]. "-" .$n1out. "-" .$rdarr[1]. "-" .$n2out;};
    if ($rdblk == 1){$idstr = $rdarr[0]. "-" .$n1out;};
    

    return $idstr;
}

?>
 

FerdieQO

Well-known member
Joined
Jul 15, 2016
Messages
213
Points
28
I think this script is a great way to generate IDs or even creating a new name for images after uploaded to hosting server.

It can apply for this case?

For example, I want to create a new site for free uploading files to my hosting. I can use use PHP and using your codes, when an user uploads their image to the server it will add a random IDs at end of file name like my-image-file-djxk-00001.jpg

Should I used Javascript in this case or use PHP codes for random file names?
 

FerdieQO

Well-known member
Joined
Jul 15, 2016
Messages
213
Points
28
I convert the script to PHP already. give it a try. Please give me a comment on how it's went. I haven't fully tested it. Thank you.
I tried your codes and it worked

Code:
<?php
echo idGenerator(4);
?>
It gave me the result

Code:
akrdo-00004
But I don't understand these code lines although I read your comments beside codes

if ($n1 < 0 || $n2 < 0 || $n3 < 0 || $lead0 < 0){ return "can't work with negative";}
if ($n2 < 1 && $n3 > 0){return "input have to follow order";}
if ($lead0 < 2){return "need at least 2";}
$n1 = ($n1 == 0)? 1 : $n1;
$format = "%'.0".$lead0."d";
$alpha = "abcdefghijklmnopqrstuvwxyz123456789";
$idstr;
$n1out = sprintf($format, $n1); $n2out = sprintf($format, $n2); $n3out = sprintf($format, $n3);
and this loop

if ($n1 > 0){$rdblk = $rdblk +1 ;}; if ($n2 > 0){$rdblk = $rdblk +1;}; if ($n3 > 0){$rdblk = $rdblk +1 ;};
$rdstr = "";
for ($i = 0; $i < $rdblk; $i++) {
for ($id = 0; $id < $lead0; $id++){
$rdstr = $rdstr . $alpha[rand(0,strlen($alpha)-1)];
}
$rdarr[$i] = $rdstr; $rdstr = "";
}
 

kevinhng86

Member
Registered
Joined
Jan 12, 2017
Messages
58
Points
0
Hi FerdieQO,
Code:
if ($n1 < 0 || $n2 < 0 || $n3 < 0 || $lead0 < 0){ return "can't work with negative";}
if ($n2 < 1 && $n3 > 0){return "input have to follow order";}
if ($lead0 < 2){return "need at least 2";}
For this 3 code line they are checking for error, the first one is if any of the input value is less than 0 then it is obvious that it will throw in error therefor it have to exit by returning an error string saying that the function can't work with negative input value. The || mean or. So in our language it mean if variable n1 < 0 or variable n2 < 0 and so on, if any of them is true than it will return the string and exit the loop. Most people would write that into 3 line.

The second code line is if n2 is less than 1 but n3 is higher than zero mean that you are trying to utilise the third block and not follow order for input so it will also return in error.

The third one is checking for length of output. If you put in any length that is 2 or less it will return in error. This is the minimum length the script is willing to work with.


Code:
$n1 = ($n1 == 0)? 1 : $n1; 
$format = "%'.0".$lead0."d";
$alpha = "abcdefghijklmnopqrstuvwxyz123456789";
$idstr; 
$n1out = sprintf($format, $n1); $n2out = sprintf($format, $n2); $n3out = sprintf($format, $n3);
For this code block if you forget to declare variable n1 is 0 than it will replace the value with 1. If it is not than it will just be variable n1 which mean whichever number it is.

The second line format is to use by sprintf, it is to make sure that the length of the non random id block will be as long as defined by variable lead0. Which mean if the length must be five but you only have number 15 than it will put out 000 in front of that 15 to make up the complete 00015.

The alpha variable are the pool of character that the generator going to draw a character from later.

idstr variable is declare here because I am used to declare variable in Javascript like this but in php you don't really have to declare variable until it is use. This post is too long so i will split in two.


Code:
if ($n1 > 0){$rdblk = $rdblk +1 ;}; if ($n2 > 0){$rdblk = $rdblk +1;}; if ($n3 > 0){$rdblk = $rdblk +1 ;};
This line of code declare how many random block is needed base on input value. Every non random block you have will add one value to this.

Code:
for ($i = 0; $i < $rdblk; $i++) {      << This is the first loop, it look at rdblk number which stand for random block. rdblk define how many random block are going to be needed.
$rdstr = "";                   << rdstr have to be declare here so every time the loop, loop through this will get reset. rdstr is use for building the random string.
for ($id = 0; $id < $lead0; $id++){    << This loop is for building the random string and base on it's length.
$rdstr = $rdstr . $alpha[rand(0,strlen($alpha)-1)];  << Each time the loop run the random string will add itself with a character from variable alpha declare above taken from a random       
                                                                                    position, The minimum of the random position is 0, the maximum length is the length of the string is the alpha variable length 
                                                                                    minus one. This is due to the position of a string start at 0 and not one. So it last position would be one below its maximum length.
} 
$rdarr[$i] = $rdstr;     << end of loop where the rdarr which stand for random array. Each index in here mean a block of random number. 
}
There is an error in this because I convert it too quickly so I mod it and explain it in the source it is easier.
 
Last edited:
Newer Threads
Replies
8
Views
5,944
Replies
2
Views
2,975
Replies
9
Views
2,866

Latest Hosting OffersNew Reviews

Sponsors

Tag Cloud

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top