From ff4f5fec1d7eee00fb2052f8f3f98a721791627f Mon Sep 17 00:00:00 2001 From: MeiMei <30769358+mei23@users.noreply.github.com> Date: Sun, 5 May 2019 09:29:15 +0900 Subject: [PATCH] meidg (#4835) --- src/misc/gen-id.ts | 2 ++ src/misc/id/meidg.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/misc/id/meidg.ts diff --git a/src/misc/gen-id.ts b/src/misc/gen-id.ts index 99cb70b3fb..7779e2db1a 100644 --- a/src/misc/gen-id.ts +++ b/src/misc/gen-id.ts @@ -1,6 +1,7 @@ import { ulid } from 'ulid'; import { genAid } from './id/aid'; import { genMeid } from './id/meid'; +import { genMeidg } from './id/meidg'; import { genObjectId } from './id/object-id'; import config from '../config'; @@ -12,6 +13,7 @@ export function genId(date?: Date): string { switch (metohd) { case 'aid': return genAid(date); case 'meid': return genMeid(date); + case 'meidg': return genMeidg(date); case 'ulid': return ulid(date.getTime()); case 'objectid': return genObjectId(date); default: throw new Error('unknown id generation method'); diff --git a/src/misc/id/meidg.ts b/src/misc/id/meidg.ts new file mode 100644 index 0000000000..d4aaaea1ba --- /dev/null +++ b/src/misc/id/meidg.ts @@ -0,0 +1,28 @@ +const CHARS = '0123456789abcdef'; + +// 4bit Fixed hex value 'g' +// 44bit UNIX Time ms in Hex +// 48bit Random value in Hex + +function getTime(time: number) { + if (time < 0) time = 0; + if (time === 0) { + return CHARS[0]; + } + + return time.toString(16).padStart(11, CHARS[0]); +} + +function getRandom() { + let str = ''; + + for (let i = 0; i < 12; i++) { + str += CHARS[Math.floor(Math.random() * CHARS.length)]; + } + + return str; +} + +export function genMeidg(date: Date): string { + return 'g' + getTime(date.getTime()) + getRandom(); +}