Javascript generate unique number based on string
You want a hash function. Hash functions are generally not unique (as in, there are collisions), but the keyspace is so vast that you might live entire lifetimes without finding one in your app.
Look for SHA1 and SHA256 implementations for JavaScript for a start, if you're using node, look at the crypto module.
Generate unique number based on string input in Javascript
All right, did allot of testing and come to this. A relative short unique id generated by the following:
o.lz = function(i,c)
{
if( typeof c != 'number' || c <= 0 || (typeof i != 'number' && typeof i != 'string') )
{ return i; }
i+='';
while( i.length < c )
{ i='0'+i; }
return i;
}
o.getHashCode = function(s)
{
var hash=0,c=(typeof s == 'string')?s.length:0,i=0;
while(i<c)
{
hash = ((hash<<5)-hash)+s.charCodeAt(i++);
//hash = hash & hash; // Convert to 32bit integer
}
return ( hash < 0 )?((hash*-1)+0xFFFFFFFF):hash; // convert to unsigned
};
o.uniqueId = function( s, bres )
{
if( s == undefined || typeof s != 'string' )
{
if( !o.___uqidc )
{ o.___uqidc=0; }
else { ++o.___uqidc; }
var od = new Date(),
i = s = od.getTime()+''+o.___uqidc;
}
else { var i = o.getHashCode( s ); }
return ((bres)?'res:':'')+i.toString(32)+'-'+o.lz((s.length*4).toString(16),3);
};
Examples:
o.uniqueId( 'M:/Mijn Muziek/Various Artists/Revs & ElBee - Tell It To My Heart.mp3' );
o.uniqueId( 'M:/Mijn Muziek/Various Artists/Dwight Yoakam - The Back Of Your Hand.Mp3');
Will produce the following id's:
dh8qi9t-114
je38ugg-120
For my purpose it seems to be unique enough, also the extra length adds some more uniqueness. Test it on filesystem with approx 40.000 mp3 files and did not found any collision.
If you think this is not the way to go, please let me know.
Generate random string/characters in JavaScript
I think this will work for you:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
console.log(makeid(5));
Create a unique number with javascript time
If you just want a unique-ish number, then
var timestamp = new Date().getUTCMilliseconds();
would get you a simple number. But if you need the readable version, you're in for a bit of processing:
var now = new Date();
timestamp = now.getFullYear().toString(); // 2011
timestamp += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString(); // JS months are 0-based, so +1 and pad with 0's
timestamp += ((now.getDate < 10) ? '0' : '') + now.getDate().toString(); // pad with a 0
... etc... with .getHours(), getMinutes(), getSeconds(), getMilliseconds()
Is there a simple way to convert a unique string of characters into a unique number in JavaScript?
Basically, you want an injective transformation f : S → N
, where S
is the set of JS strings of length 7 with characters A-Z1-9
, and N
is the set of all JS numbers.
A possible approach is considering that the strings in S
are a positional encoding of numbers, as you attempted.
However, in order to be injective (avoid collisions), you should multiply the value of each character by the basis to the power of the position.
For example, given the following table of character values
0 ⟶ 0
1 ⟶ 1
⋮ ⋮
9 ⟶ 9
A ⟶ 10
B ⟶ 11
⋮ ⋮
Z ⟶ 35
A6HJ92B
would become 10×36⁶ + 6×36⁵ + 17×36⁴ + 19×36³ + 9×36² + 2×36 + 11
, that is, 22160072099
.
You can do the conversion easily with parseInt
and toString
:
parseInt('A6HJ92B', 36); // 22160072099
(22160072099).toString(36).toUpperCase(); // "A6HJ92B"
If you want to use an arbitrary table of values, you will have to code the transformations manually.
Note that in JS, numbers are double-precision floats of 64 bits. That means there is a finite precision, and you can't store arbitrarily big integers. It won't work properly beyond this maximum
Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MAX_SAFE_INTEGER.toString(36).toUpperCase(); // "2GOSA7PA2GV"
But since your strings only have 7 characters, it should be enough.
How can I create unique IDs with JavaScript?
could you not just keep a running index?
var _selectIndex = 0;
...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
EDIT
Upon further consideration, you may actually prefer to use array-style names for your selects...
e.g.
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
then, on the server side in php for example:
$cities = $_POST['city']; //array of option values from selects
EDIT 2 In response to OP comment
Dynamically creating options using DOM methods can be done as follows:
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
var city_opt = document.createElement("option");
city_opt.setAttribute("value",city);
city_opt.appendChild(document.createTextNode(city));
newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);
assuming that the cities
array already exists
Alternatively you could use the innerHTML method.....
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);
var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;
I want to generate unique ID
If you're just looking to generate a random sequence according to that pattern, you can do so relatively easily. To ensure it's unique, you'll want to run this function and then match it against a table of previously generated IDs to ensure it has not already been used.
In my example below, I created two functions, getRandomLetters()
and getRandomDigits()
which return a string of numbers and letters the length of the argument passed to the function (default is length of 1 for each).
Then, I created a function called generateUniqueID()
which generates a new ID according to the format you specified. It checks to see if the ID already exists within a table of exiting IDs. If so, it enters a while loop which loops until a new unique ID is created and then returns its value.
const existingIDs = ['AA1111','XY1234'];
const getRandomLetters = (length = 1) => Array(length).fill().map(e => String.fromCharCode(Math.floor(Math.random() * 26) + 65)).join('');
const getRandomDigits = (length = 1) => Array(length).fill().map(e => Math.floor(Math.random() * 10)).join('');
const generateUniqueID = () => {
let id = getRandomLetters(2) + getRandomDigits(4);
while (existingIDs.includes(id)) id = getRandomLetters(2) + getRandomDigits(4);
return id;
};
const newID = generateUniqueID();
console.log(newID);
Related Topics
Nested Json: How to Add (Push) New Items to an Object
Regex - Get All Characters After Last Slash in Url
Cors - Response to Preflight Request Doesn't Pass Access Control Check
Enable Utf-8 Encoding for JavaScript
Regex to Match Words With Hyphens And/Or Apostrophes
415 (Unsupported Media Type) With Rest Post Request
How to Make Any Hovered Color Darker/Lighter That the Original
Process a Dictionary and Return Each Entry in React
Angular 6 Store Data from Json Array Inside Json
Special Character Validation Using JavaScript
How to Create Prompt With Two Input Fields
Javascript Loop Wait Until API Call Finished
Bootstrap Modal Hide Not Working With Jquery Ajax
Get Index on Click of a Mapped Array in React Js