模組資訊
模組介紹
yeast是唯一的ID生成器。它的主要目的是生成可用於緩存清除的唯一ID。通常的做法是使用時間戳記,但是使用時間戳記有幾個缺點。
- 時間戳已經是13個字符了。這可能對1個請求無關緊要,但是如果您發出數百個請求,則這會迅速增加帶寬和處理時間。
- 它不夠獨特。如果您緊接彼此生成兩個標記,則它們將是相同的,因為計時精度限制為毫秒。
yeast通過以下方式解決了這兩個問題:
- Compressing the generated timestamp using a custom
encode()
function that returns a string representation of the number. - Seeding the id in case of collision (when the id is identical to the previous one).
模組安裝
1 |
npm install --save yeast |
模組使用
加載函式庫
1 2 3 |
'use strict'; var yeast = require('yeast'); |
產生惟一識別ID
1 2 3 4 5 |
console.log(yeast(), yeast(), yeast()); // outputs: KyxidwN KyxidwN.0 KyxidwN.1 setTimeout(function () { console.log(yeast()); // outputs: KyxidwO }); |
yeast.encode(num)
1 |
yeast.encode(+new Date()); // outputs: Kyxjuo1 |
yeast.decode(str)
1 2 3 |
var id = yeast(); // holds the value: Kyxl1OU yeast.decode(id); // outputs: 1439816226334 |