Update id generation methods

This commit is contained in:
syuilo
2019-04-14 01:08:26 +09:00
parent b247be80cc
commit e64912545a
6 changed files with 30 additions and 72 deletions

23
src/misc/id/aid.ts Normal file
View File

@@ -0,0 +1,23 @@
// AID
// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの] + 長さ2の[ノイズ文字列]
import * as cluster from 'cluster';
const TIME2000 = 946684800000;
let counter = process.pid + (cluster.isMaster ? 0 : cluster.worker.id);
function getTime(time: number) {
time = time - TIME2000;
if (time < 0) time = 0;
return time.toString(36).padStart(8, '0');
}
function getRandom() {
return counter.toString(36).padStart(length, '0').substr(2);
}
export function genAid(date: Date): string {
counter++;
return getTime(date.getTime()) + getRandom();
}

26
src/misc/id/object-id.ts Normal file
View File

@@ -0,0 +1,26 @@
const CHARS = '0123456789abcdef';
function getTime(time: number) {
if (time < 0) time = 0;
if (time === 0) {
return CHARS[0];
}
time = Math.floor(time / 1000);
return time.toString(16).padStart(8, CHARS[0]);
}
function getRandom() {
let str = '';
for (let i = 0; i < 16; i++) {
str += CHARS[Math.floor(Math.random() * CHARS.length)];
}
return str;
}
export function genObjectId(date: Date): string {
return getTime(date.getTime()) + getRandom();
}