From 29c69b4c64520847fb808d8805747551a1abb5f8 Mon Sep 17 00:00:00 2001 From: zhupengfei Date: Mon, 1 Nov 2021 13:31:08 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E4=B8=89=E7=A7=8Dfu?= =?UTF-8?q?nction=E5=92=8C=E6=9B=B4=E8=AF=A6=E7=BB=86=E7=9A=84=E8=AF=B4?= =?UTF-8?q?=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JavaScript/index.js | 53 +++++++++++- TypeScript/README.md | 89 ++++++++++---------- TypeScript/snowflakeIdv1.ts | 134 ++++++++++++++++++++---------- TypeScript/snowflakeIdv1Option.ts | 43 ++++++++++ TypeScript/test/test1.ts | 2 +- TypeScript/test/test2.ts | 2 +- TypeScript/test/test3.ts | 2 +- TypeScript/test/test4.ts | 2 +- TypeScript/test/test5.ts | 2 +- 9 files changed, 231 insertions(+), 98 deletions(-) create mode 100644 TypeScript/snowflakeIdv1Option.ts diff --git a/JavaScript/index.js b/JavaScript/index.js index 989b01f..7dffae6 100644 --- a/JavaScript/index.js +++ b/JavaScript/index.js @@ -198,11 +198,60 @@ class Genid { return tempTimeTicker; } + + /** + * 生成ID + * @returns 始终输出number类型,超过时throw error + */ + NextNumber() { + if (this._IsOverCost) { + // + let id = this.NextOverCostId() + if (id >= 9007199254740992n) + throw Error(`${id.toString()} over max of Number 9007199254740992`) + + return parseInt(id.toString()) + } else { + // + let id = this.NextNormalId() + if (id >= 9007199254740992n) + throw Error(`${id.toString()} over max of Number 9007199254740992`) + + return parseInt(id.toString()) + } + } + + /** + * 生成ID + * @returns 根据输出数值判断,小于number最大值时输出number类型,大于时输出bigint + */ NextId() { if (this._IsOverCost) { - return parseInt(this.NextOverCostId()); + let id = this.NextOverCostId() + if (id >= 9007199254740992n) + return id + else + return parseInt(id) + } else { + let id = this.NextNormalId() + if (id >= 9007199254740992n) + return id + else + return parseInt(id) + } + } + + /** + * 生成ID + * @returns 始终输出bigint类型 + */ + NextBigId() { + if (this._IsOverCost) { + // + return this.NextOverCostId() } else { - return parseInt(this.NextNormalId()); + // + return this.NextNormalId() } } } diff --git a/TypeScript/README.md b/TypeScript/README.md index f0e47b5..f5c2347 100644 --- a/TypeScript/README.md +++ b/TypeScript/README.md @@ -11,14 +11,55 @@ js Number 类型最大数值:9007199254740992(16位), 在JS中没有bigint类型,所以建议将ID控制在16位以内,统一使用number类型 -执行测试代码 +## 使用 + +### 1.文件引用 + +```js +import { snowflakeIdv1 } from '../snowflakeIdv1' + +const WorkerId = process.env.WorkerId == undefined ? 1 : process.env.WorkerId + +let gen1 = new snowflakeIdv1({ WorkerId: WorkerId}) +let id1 = gen1.NextId() +console.log(id1, id1.toString().length) + +``` + +### 2.npm库安装 + +```sh +npm i simple-flakeid +``` + +```js +const snowId = require('simple-flakeid') +let gen1 = new snowId.SnowflakeIdv1({ workerId: 1 }) +for (let i = 0; i < 10; i++) { + let id1 = gen1.NextId() + console.log(`${i} ID:${id1} ${typeof id1} length:${id1.toString().length}`) +} + +``` +## function + +### function NextId() +根据输出数值判断,小于number最大值时输出number类型,大于时输出bigint + +### function NextNumber() +始终输出number类型,超过时throw error + +### function NextBigId() +始终输出bigint类型 + + +## 测试 ```bash ts-node test/test1.ts ``` - ## 使用 ```js @@ -127,50 +168,6 @@ $ ts-node test/test4.ts 8 ID:30043877339570182 bigint 长度:17 9 ID:30043877339570183 bigint 长度:17 - - - - - - - - - - - - - - - -``` - -## 同时兼容number和bigint的写法 - -如果您觉得这个用法更好,可以手动替换对应方法 - -```js - /** - * 生成ID - * @returns - */ - public NextId(): number | bigint { - if (this._IsOverCost) { - // - let id = this.NextOverCostId() - if (id >= 9007199254740992n) - return id - else - return parseInt(id.toString()) - } else { - // - let id = this.NextNormalId() - if (id >= 9007199254740992n) - return id - else - return parseInt(id.toString()) - } - } - ``` ## 其他帮助 diff --git a/TypeScript/snowflakeIdv1.ts b/TypeScript/snowflakeIdv1.ts index f84a22f..0d4f75f 100644 --- a/TypeScript/snowflakeIdv1.ts +++ b/TypeScript/snowflakeIdv1.ts @@ -1,3 +1,5 @@ +import { snowflakeIdv1Option } from "./snowflakeIdv1Option" + /** * */ @@ -78,70 +80,67 @@ export class snowflakeIdv1 { */ private _OverCostCountInOneTerm - /** - *Creates an instance of Genid. - * @author bubao - * @param {{ - * Method: 1, // 雪花计算方法,(1-漂移算法|2-传统算法),默认 1 - * BaseTime: 1577836800000, // 基础时间(ms 单位),不能超过当前系统时间 - * WorkerId: Number, // 机器码,必须由外部设定,最大值 2^WorkerIdBitLength-1 - * WorkerIdBitLength: 6, // 机器码位长,默认值 6,取值范围 [1, 15](要求:序列数位长+机器码位长不超过 22) - * SeqBitLength: 6, // 序列数位长,默认值 6,取值范围 [3, 21](要求:序列数位长+机器码位长不超过 22) - * MaxSeqNumber: 5, // 最大序列数(含),设置范围 [MinSeqNumber, 2^SeqBitLength-1],默认值 0,表示最大序列数取最大值(2^SeqBitLength-1]) - * MinSeqNumber: 5, // 最小序列数(含),默认值 5,取值范围 [5, MaxSeqNumber],每毫秒的前 5 个序列数对应编号 0-4 是保留位,其中 1-4 是时间回拨相应预留位,0 是手工新值预留位 - * TopOverCostCount: 2000// 最大漂移次数(含),默认 2000,推荐范围 500-10000(与计算能力有关) - * }} options - * @memberof Genid - */ - constructor(options: any) { - if (options.WorkerId === undefined) + *Creates an instance of Genid. + * @author zhupengfeivip + * @param {{ + * BaseTime: 1577836800000, // 基础时间(ms 单位),默认2020年1月1日,不能超过当前系统时间,一旦投入使用就不能再更改,更改后产生的ID可能会和以前的重复 + * WorkerId: Number, // 机器码,必须由外部设定,最大值 2^WorkerIdBitLength-1 + * WorkerIdBitLength: 6, // 机器码位长,默认值 6,取值范围 [1, 15](要求:序列数位长+机器码位长不超过 22) + * SeqBitLength: 6, // 序列数位长,默认值 6,取值范围 [3, 21](要求:序列数位长+机器码位长不超过 22) + * MaxSeqNumber: 5, // 最大序列数(含),设置范围 [MinSeqNumber, 2^SeqBitLength-1],默认值 0,表示最大序列数取最大值(2^SeqBitLength-1]) + * MinSeqNumber: 5, // 最小序列数(含),默认值 5,取值范围 [5, MaxSeqNumber],每毫秒的前 5 个序列数对应编号 0-4 是保留位,其中 1-4 是时间回拨相应预留位,0 是手工新值预留位 + * TopOverCostCount: 2000// 最大漂移次数(含),默认 2000,推荐范围 500-10000(与计算能力有关) + * }} options + * @memberof Genid + */ + constructor(options: snowflakeIdv1Option) { + if (options.workerId === undefined) throw new Error("lost WorkerId") - // 1.BaseTime 2020年1月1日 + // 1.BaseTime 2020年1月1日 Wed, 01 Jan 2020 00:00:00 GMT 0时区的2020年1月1日 const BaseTime = 1577836800000 - if (!options.BaseTime || options.BaseTime < 0) - options.BaseTime = BaseTime + if (!options.baseTime || options.baseTime < 0) + options.baseTime = BaseTime // 2.WorkerIdBitLength const WorkerIdBitLength = 6 - if (!options.WorkerIdBitLength || options.WorkerIdBitLength < 0) - options.WorkerIdBitLength = WorkerIdBitLength + if (!options.workerIdBitLength || options.workerIdBitLength < 0) + options.workerIdBitLength = WorkerIdBitLength // 4.SeqBitLength const SeqBitLength = 6 - if (!options.SeqBitLength || options.SeqBitLength < 0) - options.SeqBitLength = SeqBitLength + if (!options.seqBitLength || options.seqBitLength < 0) + options.seqBitLength = SeqBitLength // 5.MaxSeqNumber - const MaxSeqNumber = (1 << SeqBitLength) - 1 - if (options.MaxSeqNumber <= 0 || options.MaxSeqNumber === undefined) { - options.MaxSeqNumber = MaxSeqNumber - } + if (options.maxSeqNumber == undefined || options.maxSeqNumber <= 0) + options.maxSeqNumber = (1 << SeqBitLength) - 1 + // 6.MinSeqNumber const MinSeqNumber = 5 - if (!options.MinSeqNumber || options.MinSeqNumber < 0) - options.MinSeqNumber = MinSeqNumber + if (options.minSeqNumber == undefined || options.minSeqNumber < 0) + options.minSeqNumber = MinSeqNumber // 7.Others const topOverCostCount = 2000 - if (!options.TopOverCostCount || options.TopOverCostCount < 0) - options.TopOverCostCount = topOverCostCount + if (options.topOverCostCount == undefined || options.topOverCostCount < 0) + options.topOverCostCount = topOverCostCount - if (options.Method !== 2) - options.Method = 1 + if (options.method !== 2) + options.method = 1 else - options.Method = 2 + options.method = 2 - this.Method = BigInt(options.Method) - this.BaseTime = BigInt(options.BaseTime) - this.WorkerId = BigInt(options.WorkerId) - this.WorkerIdBitLength = BigInt(options.WorkerIdBitLength) - this.SeqBitLength = BigInt(options.SeqBitLength) - this.MaxSeqNumber = BigInt(options.MaxSeqNumber) - this.MinSeqNumber = BigInt(options.MinSeqNumber) - this.TopOverCostCount = BigInt(options.TopOverCostCount) + this.Method = BigInt(options.method) + this.BaseTime = BigInt(options.baseTime) + this.WorkerId = BigInt(options.workerId) + this.WorkerIdBitLength = BigInt(options.workerIdBitLength) + this.SeqBitLength = BigInt(options.seqBitLength) + this.MaxSeqNumber = BigInt(options.maxSeqNumber) + this.MinSeqNumber = BigInt(options.minSeqNumber) + this.TopOverCostCount = BigInt(options.topOverCostCount) const timestampShift = this.WorkerIdBitLength + this.SeqBitLength const currentSeqNumber = this.MinSeqNumber @@ -156,6 +155,7 @@ export class snowflakeIdv1 { this._OverCostCountInOneTerm = 0 } + /** * 当前序列号超过最大范围,开始透支使用序号号的通知事件,,本项暂未实现 * @returns @@ -326,9 +326,53 @@ export class snowflakeIdv1 { /** * 生成ID - * @returns + * @returns 始终输出number类型,超过时throw error + */ + public NextNumber(): number { + if (this._IsOverCost) { + // + let id = this.NextOverCostId() + if (id >= 9007199254740992n) + throw Error(`${id.toString()} over max of Number 9007199254740992`) + + return parseInt(id.toString()) + } else { + // + let id = this.NextNormalId() + if (id >= 9007199254740992n) + throw Error(`${id.toString()} over max of Number 9007199254740992`) + + return parseInt(id.toString()) + } + } + + /** + * 生成ID + * @returns 根据输出数值判断,小于number最大值时输出number类型,大于时输出bigint + */ + public NextId(): number | bigint { + if (this._IsOverCost) { + // + let id = this.NextOverCostId() + if (id >= 9007199254740992n) + return id + else + return parseInt(id.toString()) + } else { + // + let id = this.NextNormalId() + if (id >= 9007199254740992n) + return id + else + return parseInt(id.toString()) + } + } + + /** + * 生成ID + * @returns 始终输出bigint类型 */ - public NextId(): bigint { + public NextBigId(): bigint { if (this._IsOverCost) { // return this.NextOverCostId() diff --git a/TypeScript/snowflakeIdv1Option.ts b/TypeScript/snowflakeIdv1Option.ts new file mode 100644 index 0000000..c4a2667 --- /dev/null +++ b/TypeScript/snowflakeIdv1Option.ts @@ -0,0 +1,43 @@ +export class snowflakeIdv1Option { + + /** + * 雪花计算方法,(1-漂移算法|2-传统算法),默认 1 + */ + method?: number = 1 + + /** + * 机器码,必须由外部设定,最大值 2^WorkerIdBitLength-1 + */ + workerId: number = 1 + + /** + * 机器码位长,默认值 6,取值范围 [1, 15](要求:序列数位长+机器码位长不超过 22) + */ + workerIdBitLength?: number = 6 + + /** + * 基础时间(ms 单位),不能超过当前系统时间, 默认2020年1月1日 + */ + baseTime?: number = 1577836800000 + + /** + * 最大序列数(含),设置范围 [MinSeqNumber, 2^SeqBitLength-1],默认值 0,表示最大序列数取最大值(2^SeqBitLength-1]) + */ + maxSeqNumber?: number = undefined + + /** + * 最小序列数(含),默认值 5,取值范围 [5, MaxSeqNumber],每毫秒的前 5 个序列数对应编号 0-4 是保留位,其中 1-4 是时间回拨相应预留位,0 是手工新值预留位 + */ + minSeqNumber?: number = 5 + + /** + * 序列数位长,默认值 6,取值范围 [3, 21](要求:序列数位长+机器码位长不超过 22) + */ + seqBitLength?: number = 6 + + /** + * 最大漂移次数(含),默认 2000,推荐范围 500-10000(与计算能力有关) + */ + topOverCostCount?: number = 2000 + +} \ No newline at end of file diff --git a/TypeScript/test/test1.ts b/TypeScript/test/test1.ts index 5041b27..4b4e322 100644 --- a/TypeScript/test/test1.ts +++ b/TypeScript/test/test1.ts @@ -2,6 +2,6 @@ import { snowflakeIdv1 } from '../snowflakeIdv1' const WorkerId = process.env.WorkerId == undefined ? 1 : process.env.WorkerId -let gen1 = new snowflakeIdv1({ WorkerId: WorkerId }) +let gen1 = new snowflakeIdv1({ workerId: 1 }) let id1 = gen1.NextId() console.log(`ID:${id1} 长度:${id1.toString().length}`) \ No newline at end of file diff --git a/TypeScript/test/test2.ts b/TypeScript/test/test2.ts index f41bd28..c3b712a 100644 --- a/TypeScript/test/test2.ts +++ b/TypeScript/test/test2.ts @@ -8,7 +8,7 @@ const Method = process.env.Method == undefined ? 1 : process.env.Method console.log("WorkerId:" + WorkerId) console.log("Method:" + Method) console.log("--------------------") -let gen1 = new snowflakeIdv1({ WorkerId: WorkerId, Method: Method }) +let gen1 = new snowflakeIdv1({ workerId: 1 }) diff --git a/TypeScript/test/test3.ts b/TypeScript/test/test3.ts index 1957567..95f2876 100644 --- a/TypeScript/test/test3.ts +++ b/TypeScript/test/test3.ts @@ -4,6 +4,6 @@ const WorkerId = process.env.WorkerId == undefined ? 1 : process.env.WorkerId const Method = process.env.Method == undefined ? 1 : process.env.Method -let gen1 = new snowflakeIdv1({ WorkerId: WorkerId, Method: Method }) +let gen1 = new snowflakeIdv1({ workerId: 1 }) let id1 = gen1.NextId() console.log(id1, id1.toString().length) \ No newline at end of file diff --git a/TypeScript/test/test4.ts b/TypeScript/test/test4.ts index ab51f36..e4f88f4 100644 --- a/TypeScript/test/test4.ts +++ b/TypeScript/test/test4.ts @@ -2,7 +2,7 @@ import { snowflakeIdv1 } from '../snowflakeIdv1' const WorkerId = process.env.WorkerId == undefined ? 1 : process.env.WorkerId -let gen1 = new snowflakeIdv1({ WorkerId: WorkerId, SeqBitLength: 10 }) +let gen1 = new snowflakeIdv1({ workerId: 1, seqBitLength: 10 }) for (let i = 0; i < 10; i++) { let id1 = gen1.NextId() console.log(`${i} ID:${id1} ${typeof id1} 长度:${id1.toString().length}`) diff --git a/TypeScript/test/test5.ts b/TypeScript/test/test5.ts index 5877aca..fb921c2 100644 --- a/TypeScript/test/test5.ts +++ b/TypeScript/test/test5.ts @@ -2,7 +2,7 @@ import { snowflakeIdv1 } from '../snowflakeIdv1' const WorkerId = process.env.WorkerId == undefined ? 1 : process.env.WorkerId -let gen1 = new snowflakeIdv1({ WorkerId: WorkerId, SeqBitLength: 10 }) +let gen1 = new snowflakeIdv1({ workerId: 1, seqBitLength: 10 }) // for (let i = 0; i < 10; i++) { // let id1 = gen1.NextId() // console.log(`${i} ID:${id1} ${typeof id1} 长度:${id1.toString().length}`) -- GitLab