V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
aleung
V2EX  ›  分享创造

AnyID - 万能的 ID 生成器

  •  1
     
  •   aleung · 2017-02-23 13:52:16 +08:00 · 2848 次点击
    这是一个创建于 2591 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    项目地址: https://github.com/aleung/node-anyid

    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 是阅读友好的:排除了字母 IO 因为容易和数字 10混淆。

    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
    
    1 条回复    2017-02-24 10:42:06 +08:00
    Wichna
        1
    Wichna  
       2017-02-24 10:42:06 +08:00
    非常赞👍
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5235 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 07:23 · PVG 15:23 · LAX 00:23 · JFK 03:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.