diff --git a/src/id.ts b/src/id.ts new file mode 100644 index 0000000..49bcb92 --- /dev/null +++ b/src/id.ts @@ -0,0 +1,21 @@ +/** + * nanoid 中导出 {@link https://github.com/ai/nanoid} + */ +const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +/** + * 生成简易 {@link https://github.com/ai/nanoid|nanoid},使用 nanoid 中导出的字母表 + * + * @param size + * @param dict + * @returns id + * @example nid() // => 'nZZyknCBT5ra_gGE' + */ +export function nid(size = 16, dict = urlAlphabet): string { + let id = '' + let i = size + const len = dict.length + while (i--) + id += dict[(Math.random() * len) | 0] + return id +} diff --git a/src/string.ts b/src/string.ts index cfd59cb..242e4ca 100644 --- a/src/string.ts +++ b/src/string.ts @@ -1,24 +1,3 @@ -/** - * nanoid 中导出 {@link https://github.com/ai/nanoid} - */ -const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' - -/** - * 生成随机字符串 - * @param size - * @param dict - * @returns 随机字符串 - * @example randomStr() // => 'nZZyknCBT5ra_gGE' - */ -export function randomStr(size = 16, dict = urlAlphabet): string { - let id = '' - let i = size - const len = dict.length - while (i--) - id += dict[(Math.random() * len) | 0] - return id -} - /** * 将字符串中的 \ 转换为 / * @param str diff --git a/test/id.test.ts b/test/id.test.ts new file mode 100644 index 0000000..886f9b3 --- /dev/null +++ b/test/id.test.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from 'vitest' +import { nid } from '../src/id' + +describe('string', () => { + describe('nid Function', () => { + it('应该生成随机字符串', () => { + expect(nid()).toHaveLength(16) + }) + }) +}) diff --git a/test/string.test.ts b/test/string.test.ts index 0380b10..09b1d44 100644 --- a/test/string.test.ts +++ b/test/string.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest' import { ensurePrefix, ensureSuffix, - randomStr, slash, trim, trimAll, @@ -11,12 +10,6 @@ import { } from '../src/string' describe('string', () => { - describe('randomStr Function', () => { - it('应该生成随机字符串', () => { - expect(randomStr()).toHaveLength(16) - }) - }) - describe('slash Function', () => { it('应该将字符串中的 \ 转换为 /', () => { expect(slash('hello\\world')).toBe('hello/world')