Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

生成不重复的随机字符串 #19

Closed
Dream4ever opened this issue May 26, 2018 · 0 comments
Closed

生成不重复的随机字符串 #19

Dream4ever opened this issue May 26, 2018 · 0 comments
Labels
Back-end Where data really come and go Front-end Everything you see and experience JS Javascript

Comments

@Dream4ever
Copy link
Owner

Dream4ever commented May 26, 2018

需求描述

业务上的一个需求,要批量生成不重复的随机字符串。

方案调研

调研过程

先尝试 Google js generate many random strings,第一条结果就是 Stack Overflow 的,点进去看看:

Generate random string/characters in JavaScript

回答里面,有说用 Math.random() 方法的,有说用 Node.js 的 crypto 这个库的,还有说用 uuid 之类的库的。

看了这篇问答拿不定主意,于是再 Google node crypto randombytes duplicate,第一条结果是 node-hat 的 issue,里面有个高分回答也建议用 Node.js 的 crypto 这个库中的 randomBytes 方法。

在 Google 出来的第二条结果 Secure random values (in Node.js) 中,也是既有人推荐用 Node.js 的 crypto 这个库(更加原生),也有人推荐用 uuid 之类的库(更能确保唯一性,但其实没啥区别)。

几个链接看下来,最后自己的结论就是:Node.js 的 crypto,和 uuid 这类的库都可以满足自己的需求。

另外,uuid 这个库只能以一种固定格式 1c572360-faca-11e7-83ee-9d836d45ff41 生成随机字符串,而 nanoid 这个库则可以自定义所生成的字符串的长度,可以自定义字符串中包含哪些字符,在自定义性上更胜一筹。

入选方案

  • nanoid:可以自定义所生成的字符串的长度,可以自定义字符串中包含哪些字符,在自定义性上更胜一筹。

排除方案

  • uuid:只能以一种固定格式 1c572360-faca-11e7-83ee-9d836d45ff41 生成随机字符串。

应用过程

略。

要点总结

重要的事情有三点:

  • Google,不要百度。
  • 可以的话,尽量用英文作为关键字搜索。
  • Stack Overflow 上的讨论质量往往都很高,建议优先参考。

最后还是想说,GitHub 真是个宝库啊。

@Dream4ever Dream4ever added Front-end Everything you see and experience Back-end Where data really come and go JS Javascript labels May 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Back-end Where data really come and go Front-end Everything you see and experience JS Javascript
Projects
None yet
Development

No branches or pull requests

1 participant