万能 ID 生成器 Node-AnyID

码农软件 · 软件分类 · 常用工具包 · 2019-08-13 12:26:30

软件介绍

在程序里经常都需要生成一些特定格式的 id ,每种场合的需求都可能有些不一样,虽然写起来代码不复杂,但零零碎碎的东西做多了也挺烦的,于是设计了这个用于 node.js 的万能 ID 生成器。

AnyID 生成的 ID 为字符串(也可以纯数字),信息密度尽可能的高,也就是用最少的位数表示尽量多的信息。

AnyID 设计的首要考虑原则是 API 的直观易用。看看这些例子:

指定长度,随机值填充

21 个字符,包含大写小写字母和数字。 这个 ID 的碰撞可能性跟 type 4 (random) UUID 一样低。

const ids = anyid().encode('Aa0').length(21).random()
const id  = ids.id();
1LrKcmd0uk1Ma8szUxtda

多个分段

第一段根据进程号生成,第二段根据时间生成。

const ids = anyid()
  .encode('0A-IO')
  .section( anyid().fixed(process.pid) )
  .delimiter('-')
  .section( anyid().time() );

生成的 ID 是阅读友好的:排除了字母 I 和 O 因为容易和数字 1和 0混淆。

008CL-00TYMZS0P3

自增序列,指定位(bit)长度

这是生成 Twitter Snowflake 风格的 ID ,包含了时间, 序列号和 worker 标识。

const ids = anyid()
  .encode('0')
  .bit(41).time().since(new Date('2016-7-1'))
  .bit(12).seq().resetByTime();
  .bit(10).fix(workerId);

为了节省位空间,微秒时间从 2016-7-1 算起。

071243223959339218

函数值

每次生成 ID 时调用函数获得返回值。第一段是秒,第二段是纳秒。

const nanotime = () => {
  return process.hrtime()[1];
};

const ids = anyid()
  .encode('Aa0')
  .section( anyid().time('s') )
  .delimiter('+')
  .section( anyid().of(nanotime) );
BlX6bX+j3Uz0

参数绑定

第一二段的值在调用时通过传入参数给出

const ids = anyid()
  .encode('Aa0')
  .section( anyid().variable('countryId') )
  .delimiter('-')
  .section( anyid().variable('userId') )
  .delimiter('-')
  .section( anyid().length(5).random() );

const id = ids.id({ countryId: 86, userId: 635023 });
AAABY-ACpMT-EBwQJ

本文地址:https://www.codercto.com/soft/d/12270.html

Discrete Mathematics and Its Applications

Discrete Mathematics and Its Applications

Kenneth H Rosen / McGraw-Hill Science/Engineering/Math / 2003-04-22 / USD 132.81

Discrete Mathematics and its Applications is a focused introduction to the primary themes in a discrete mathematics course, as introduced through extensive applications, expansive discussion, and deta......一起来看看 《Discrete Mathematics and Its Applications》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换