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/