javascript - 根据输入生成随机 6 个字符

标签 javascript math

根据输入生成随机 6 个字符。就像我想将 1028797107357892628 转换为 j4w8p 。或者将 102879708974181177 转换为 lg36k 但我希望它保持一致。就像每当我喂入 1028797107357892628 时,它应该总是吐出 j4w8p。这可能吗? (如果可能的话,没有数据库。)我知道如何生成随机 6 个字符但我不知道如何将它与输入连接。我将不胜感激任何帮助,谢谢。

let rid = (Math.random() + 1).toString(36).substring(7); 

最佳答案

您可以创建自定义哈希函数,您的代码的一个简单函数就是

const seed = "1028797089741811773";

function customHash(str, outLen){
  //The 4 in the next regex needs to be the length of the seed divided by the desired hash lenght
  const regx = new RegExp(`.{1,${Math.floor(str.length / outLen)}}`, 'g')
  const splitted = str.match(regx);
  
 
  
  let out = "";
  for(const c of splitted){
    let ASCII = c % 126;
    if( ASCII < 33) ASCII = 33
  
   out += String.fromCharCode(ASCII)
  }

  return out.slice(0, outLen)
}


const output = customHash(seed, 6)

console.log(output)

关于javascript - 根据输入生成随机 6 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74008903/

相关文章:

javascript - 使用 typescript 的 IResourceClass 扩展 angularjs 的 $resource

javascript - $(这个)引用

javascript - jquery 附加的 html 不起作用

math - CAS - 二叉树替代方案

image - 如何对 RGB 值执行双线性插值?

javascript - javascript 中命名空间和标识符之间的区别

javascript - Initiate Masonry - 在无限滚动和参数搜索之后

javascript - 如何制作齿轮啮合

用于解析 Latex 或 MathML 字符串的 Java 或 scala 库

algorithm - 从 int 和余数中找到作为 float 的平方根?