Skip to content

Commit

Permalink
feat(utils): 新增 toFullWidthString
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 2, 2022
1 parent be3ca28 commit 9f9295f
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export * from './sampleIndex'
export * from './selectDom'
export * from './signal'
export * from './swap'
export * from './toFullWidthString'
export * from './toHalfWidthString'
export * from './traverse'
export * from './TreeData'
Expand Down
13 changes: 13 additions & 0 deletions src/utils/toFullWidthString.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { toFullWidthString } from './toFullWidthString'

describe('toFullWidthString', () => {
test('ok', () => {
expect(toFullWidthString(' ')).toBe(' ')
expect(toFullWidthString('1234567890')).toBe('1234567890')
expect(toFullWidthString('abcdefghijklmnopqrstuvwxyz')).toBe(
'abcdefghijklmnopqrstuvwxyz',
)
expect(toFullWidthString(',@!#&()%{}')).toBe(',@!#&()%{}')
expect(toFullWidthString('[]"".$*')).not.toBe('【】“”。¥×')
})
})
20 changes: 20 additions & 0 deletions src/utils/toFullWidthString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* 转换为全角字符串。
*
* @param value 要转换的字符串
* @returns 返回转换后的全角字符串
*/
export function toFullWidthString(value: string): string {
let result = ''
for (let i = 0; i < value.length; i++) {
const charCode = value.charCodeAt(i)
if (charCode === 32) {
result += String.fromCharCode(12288)
} else if (charCode < 127) {
result += String.fromCharCode(value.charCodeAt(i) + 65248)
} else {
result += String.fromCharCode(value.charCodeAt(i))
}
}
return result
}
2 changes: 1 addition & 1 deletion src/utils/toHalfWidthString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function toHalfWidthString(value: string): string {
for (let i = 0; i < value.length; i++) {
const charCode = value.charCodeAt(i)
if (charCode === 12288) {
result += String.fromCharCode(charCode - 12256)
result += String.fromCharCode(32)
} else if (charCode > 65280 && charCode < 65375) {
result += String.fromCharCode(charCode - 65248)
} else {
Expand Down

0 comments on commit 9f9295f

Please sign in to comment.