在JavaScript中生成随机且唯一的字符串

As I was building the platform for my online course I had the problem of generating a few thousands unique URLs.

在为在线课程构建平台时,我遇到了生成数千个唯一URL的问题。

Every person taking the course will be assigned a unique URL. The backend knows about all those URLs and maps a valid URL to the course content.

每个参加该课程的人都将被分配一个唯一的URL。 后端知道所有这些URL,并将有效的URL映射到课程内容。

I wanted a unique URL because I can associate a URL to a purchase email.

我想要一个唯一的URL,因为我可以将URL与购买电子邮件相关联。

In this way, I can avoid having a login, and at the same time having a separate URL for each person lets me block eventual abuse if that URL gets unintentionally or intentionally shared in the public.

这样,我可以避免登录,同时为每个人使用单独的URL可以阻止最终滥用,如果该URL被无意或有意在公众中共享。

So I set out to write my Node.js script.

因此,我开始编写我的Node.js脚本。

I used the randomstring package, and I added numbers to a Set object until I got the number I wanted. Using a Set means every string will be unique because calling add and passing a duplicate string will silently do nothing.

我使用了randomstring程序包,然后将数字添加到Set对象中,直到获得所需的数字为止。 使用Set意味着每个字符串都是唯一的,因为调用add并传递重复的字符串将无提示地执行任何操作。

I made a generateStrings() function that returns the set:

我做了一个generateStrings()函数来返回集合:

const generateStrings = (numberOfStrings, stringLength) => {
  const randomstring = require('randomstring')
  const s = new Set()

  while (s.size < numberOfStrings) {
    s.add(randomstring.generate(stringLength))
  }

  return s
}

I can call it using

我可以用

const strings = generateStrings(100, 20)

where 100 is the number of strings I want, and 20 is the length of each string.

其中100是我想要的字符串数,而20是每个字符串的长度。

Once we get the set, we can iterate over them using the values() Set method:

一旦获得集合,就可以使用values() Set方法对其进行迭代:

for (const value of strings.values()) {
  console.log(value)
}

翻译自: https://flaviocopes.com/javascript-generate-random-unique-strings/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值