1

I am trying to generate a unique random string.

var string = Math.floor( Math.random() * 1000 ) + Date.now();

The above method which I am using right now gives me too long a string and I want a shorter unique one.

vitally
  • 377
  • 6
  • 17
  • the above method which i am using right now gives me a too long string and i want the short and unique one. – vitally May 11 '15 at 10:46
  • how many characters you want? – Tushar May 11 '15 at 10:46
  • Where are you storing the generated codes to verify that any new ones are unique? – Rory McCrossan May 11 '15 at 10:52
  • If you want it to be unique you have to keep track of them in some way and reference that data every time you create a new one to make sure it's not a dupe. – Tech Savant May 11 '15 at 10:52
  • 1
    @vitally You can use timestamp. It will be always unique – Tushar May 11 '15 at 10:53
  • `Date.now();` will return always a unique number. – kosmos May 11 '15 at 10:53
  • @Tushar my current method generates a string like this : 1431341525301. in which the numbers start changing from the unit place number. i want 7 characters only – vitally May 11 '15 at 10:54
  • @kmsdev not if you have two people requesting the date at the same time. Unlikely yes, but certainly possible, so it's a long way from being guaranteed unique. – Rory McCrossan May 11 '15 at 10:54
  • It's hard but possible, true. So, the workaround is to store the ids and check if it's already used (using any method to create the ids). – kosmos May 11 '15 at 10:56
  • i know that the date function generates a unique number all the time. but is there any other methods to generate a unique string may be by characters. – vitally May 11 '15 at 10:58
  • possible duplicate of [Generate a string of 5 random characters in JavaScript](http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript) – urbz May 11 '15 at 11:00
  • For invoice numbers, it would be better to generate them server-side, e.g. using [UUID v4](http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid/15875555#15875555). – Ja͢ck May 11 '15 at 11:30

3 Answers3

2

Here is a workaround to avoid the issue of repeated ids:

var GenRandom =  {

    Stored: [],

    Job: function(){
        var newId = Date.now().toString().substr(6); // or use any method that you want to achieve this string

        if( this.Check(newId) ){
            this.Job();
        }

        this.Stored.push(newId);
        return newId; // or store it in sql database or whatever you want

    },

    Check: function(id){
        for( var i = 0; i < this.Stored.length; i++ ){
            if( this.Stored[i] == id ) return true;
        }
        return false;
    }

};

jsFiddle

kosmos
  • 4,253
  • 1
  • 18
  • 36
  • becuse i dont want to run select query every time just to check that the number is already present or not – vitally May 11 '15 at 11:34
  • By this way you can be sure that no id will be repeated using JS. If you have stored your unique ids into database, a workaround is to fill `GenRandom.Stored` with current ids from db, so you only need one query to retrieve all already used ids and store it into our js array. All depends on what you want to achieve – kosmos May 11 '15 at 11:39
  • you mean without checking for " already present id's " in database. i can easily use this method. right ? – vitally May 11 '15 at 11:43
  • Yes, that's what I meant. I think yes, this is a valid (and easy) workaround for you. – kosmos May 11 '15 at 11:48
1

Based on Tushar's suggestion, (new Date().getTime()+'').substr(6,7) will give you a 7-digits unique number. Not random, but unique... at least for a certain time. Since it's based on timestamp, it is actually milliseconds time. Since the length is 7 digits, it will loop from 0000000 to 9999999 every 1000 seconds, that's roughly 17 minutes. But you can't expect a higher "level of uniqueness" with only 7 digits. It may be enough for your application, depending on what you want to achieve with that.

Edit

Following up with your comment : you want a unique SECOND number, so millisecond is no use to you (should have mentioned the seconds in your question).

You could give an invoice the number of the current second, which is (new Date().getTime()+'').substr(3,7). That would be perfect, if the unique number was not limited to 7 digits. This makes 9.999.999 possible seconds, which is... around 115 days. With 9 digits, you could print unique invoices numbers every second for 316 years.

So in my opinion, your only solution is just to start counting invoices from 0000001, then 0000002, etc, and keeping track of that somewhere to ensure uniqueness. I don't get how generating a random number between 0 and 9.999.999 will make invoices numbering more efficient or easier to track.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • i am developing an application and it requires a INVOICE NUMBER. invoice no. are always different. so that's why i want a unique string of number every second or for every bill. – vitally May 11 '15 at 11:10
0

For an invoice number you should guarantee a unique identifier no matter how long. In which case I'll suggest using an UUID/GUID. See http://guid.us/GUID/PHP for two implementations (windows-COM/non-windows). If you are not familiar with the concept of UUID, check wikipedia here: http://en.wikipedia.org/wiki/Universally_unique_identifier .

Another option for you is to use mysql's native uuid generator:

select uuid();

This you can also use in your insert queries, like:

insert into mytable (id, data) values (uuid(), 'mytext');

Of course your table structure needs to be adjusted. Personally I find it best to use traditional integer auto_inc id as primary key, along with a guid field to use in replication/export/etc as key.

EDIT: There apparently is also a uuid_short() function in mysql (since 5.1.20).

SELECT UUID_SHORT();
92395783831158784

See https://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_uuid-short

Tuncay Göncüoğlu
  • 1,699
  • 17
  • 21