I have two data objects, the user and a record.
The user should have a unique id, the record should have one too. The record has an owner, the user, each record contains the userId. So I created a simple Id generator
$( document ).ready(function() {
$("#btn").click(function(){
createId();
});
});
var myIds = [];
function createId(){ // Create new ID and push it to the ID collection
var id = generateNewId();
myIds.push(id);
console.log("The current id is: ");
console.log(id);
console.log("The array contains: ");
console.log(myIds);
}
function generateNewId(){ // Check for existing IDs
var newId = getNewId();
if($.inArray(newId, myIds) > -1){ // Does it already exist?
newId = generateNewId(); //
}
else{
return newId;
}
}
function getNewId(){ // ID generator
var possibleChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var serialLength = 20;
var generatedId = '';
for (var i = 0; i < serialLength; i++) {
var randomNumber = Math.floor(Math.random() * possibleChars.length);
generatedId += possibleChars.substring(randomNumber, randomNumber + 1);
}
return generatedId;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Add new ID</button>
So this generator works fine for both ids. But what is the correct way in generating user ids?
Is there a way to generate a unique user id when creating an account in country ? at the time ? by user ?
The record object has an ID too, is there a way to make it contain parts of its owner, the user id?
The shown generator is able to create a large range of possible ids. But what happens, when there is no possibility anymore? That's why I want a "better" way of creating IDs.