根据Javascript中的字符串输入生成唯一编号

Cod*_*eat 5 javascript string numbers unique

在过去,我创建了一个从字符串生成唯一ID(数字)的函数.今天我发现它不是那么独特.从来没有看到过问题.今天,两个不同的输入生成相同的id(数字).

我在Delphi,C++,PHP和Javascript中使用相同的技术来生成相同的id,因此当项目涉及不同的语言时没有区别.例如,对于HTML id,tempfiles等,这可以很方便地进行通信.

通常,我所做的是计算字符串的CRC16,添加总和并返回它.

例如,这两个字符串生成相同的id(数字):

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');
Run Code Online (Sandbox Code Playgroud)

它们都生成了224904的id.

以下示例是一个javascript示例.我的问题是,我怎样才能避免(稍微改变)它产生重复?(如果您可能想知道'o.'的含义,它是这些函数所属的对象):

o.getCrc16 = function(s, bSumPos) {
  if(typeof s !== 'string' || s.length === 0) {
    return 0;
  }
  var crc = 0xFFFF,
    L = s.length,
    sum = 0,
    x = 0,
    j = 0;
  for(var i = 0; i < L; i++) {
    j = s.charCodeAt(i);
    sum += ((i + 1) * j);
    x = ((crc >> 8) ^ j) & 0xFF;
    x ^= x >> 4;
    crc = ((crc << 8) ^ (x << 12) ^ (x << 5) ^ x) & 0xFFFF;
  }
  return crc + ((bSumPos ? 1 : 0) * sum);
}
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.getCrc16(s, true);
  }
  return((bres) ? 'res:' : '') + (i + (i ? s.length : 0));
};
Run Code Online (Sandbox Code Playgroud)

如何使用对代码的一点改动来避免重复?

Cod*_*eat 5

好的,做了大量的测试并且来了.由以下内容生成的相对较短的唯一ID:

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);  
};
Run Code Online (Sandbox Code Playgroud)

例子:

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');
Run Code Online (Sandbox Code Playgroud)

将产生以下id:

dh8qi9t-114
je38ugg-120
Run Code Online (Sandbox Code Playgroud)

为了我的目的,它似乎足够独特,额外的长度也增加了一些独特性.在大约40.000个mp3文件的文件系统上测试它并没有发现任何冲突.

如果您认为这不是可行的方法,请告诉我.