Skip to content

Commit

Permalink
perf: randomStr 替换至 nid
Browse files Browse the repository at this point in the history
  • Loading branch information
Ares-Chang committed Sep 5, 2024
1 parent d03090a commit 5a6f239
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 28 deletions.
21 changes: 21 additions & 0 deletions src/id.ts
Original file line number Diff line number Diff line change
@@ -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
}
21 changes: 0 additions & 21 deletions src/string.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
10 changes: 10 additions & 0 deletions test/id.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
})
7 changes: 0 additions & 7 deletions test/string.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest'
import {
ensurePrefix,
ensureSuffix,
randomStr,
slash,
trim,
trimAll,
Expand All @@ -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')
Expand Down

0 comments on commit 5a6f239

Please sign in to comment.