0

I want to generate the random id for the uploaded images with their file names.

my code is

var getUniqueMacroName = function(filename){
    var Name = $.trim(filename.replace(/.[^.]+$/,'').replace(/ /g, "").replace(/[^\w]|_/g, "").toUpperCase());
    var Ext = $.trim(filename.replace(/^.*\./,'').toUpperCase());
    var mac= _.map($("#data").DataTable().data(), function(a){return a[0]});

    var fileRand = Name.substring(0, (10 - fileExt.length));

    while(_.contains(mac, ("GM" + fileRand + fileExt))){
        var rand = Math.min(Math.floor((Math.random() * fileRand.length) + 5), (fileRand.length - 1));
        fileRand =  (fileRand.substring(0, rand) + rand + fileRand.substring(rand, fileRand.length)).substring(0, (10 - Ext.length));
    }
    return "GM" + fileRand + Ext;
}

If i upload the images like

  1. gallery image 320 1.jpg

  2. gallery image 320 2.jpg

  3. gallery image 320 3.jpg

  4. gallery image 320 4.jpg

  5. gallery image 320 5.jpg

  6. gallery image 320 6.jpg

the sixth image is execute infinite times in the while condition.This will happen when the uploaded image name have almost same.So the browser will be not respond.

Is there any way to generate the unique id for any type of file names(including the same filename) in javascript or jquery.

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
kalles
  • 337
  • 1
  • 6
  • 22

2 Answers2

0

Editted by user suggestion usefull answer;

Yes you can use TimeStamp for unique ID with Date.now(); It generate milliseconds and they are always unique;

The now() method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as a Number.

var getUniqueMacroName = function(filename){
    var Name = $.trim(filename.replace(/.[^.]+$/,'').replace(/ /g, "").replace(/[^\w]|_/g, "").toUpperCase());
    var Ext = $.trim(filename.replace(/^.*\./,'').toUpperCase());
    var mac= _.map($("#data").DataTable().data(), function(a){return a[0]});
    // dont need anymore control unique
    var fileRand = Date.getTime();
    fileRand = fileRand.substr(fileRand.length - 10);
    return "GM" + fileRand + Ext;
}
hurricane
  • 6,521
  • 2
  • 34
  • 44
0

Your approach could work if you generate a longer 'random' number?

var random = Math.random()*100000000000000000;  // e.g. 6137274974025786
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
  • It's generate random number not unique number. If you use 10 number for random probability is 1/10. If you use 100000000000000000 number for random probability is 1/100000000000000000 so it's not a unique! If you use dateTime it's always count beacuse time always increase. – hurricane Sep 11 '15 at 10:50
  • no, Date.getTime() is not unique (not always incrementing), see [my answer](http://stackoverflow.com/a/20523888/1183010). – R. Oosterholt Sep 11 '15 at 11:33