-
Notifications
You must be signed in to change notification settings - Fork 285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(utils): add comments, ts type declarations, and vitest test cases to utils functions #3154
base: dev
Are you sure you want to change the base?
Conversation
…s to utils functions
WalkthroughThis pull request introduces extensive improvements across multiple utility modules. It adds comprehensive test suites and enhances type safety by introducing TypeScript generics, explicit type annotations, and detailed JSDoc comments. Several functions have received clearer documentation and interface definitions, notably in the afterLeave, array, bigInt, calendar, date, debounce, decimal, and validation utilities. Additionally, a new Vitest configuration file has been added to streamline test executions. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant afterLeave
participant Instance
participant Timer
participant Callback
Caller->>afterLeave: Invoke afterLeave(instance, callback, speed, once)
Note over afterLeave: Validate parameters and determine listener type
afterLeave->>Instance: Register event listener ($on or $once)
Timer-->>afterLeave: Signal passage of specified delay (speed)
afterLeave->>Callback: Execute callback with proper parameters
Suggested labels
Suggested reviewers
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure. 🔧 ESLint
packages/utils/src/array/__tests__/index.test.tsOops! Something went wrong! :( ESLint: 8.57.1 ESLint couldn't find the plugin "eslint-plugin-vue". (The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:
The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue". If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. packages/utils/src/after-leave/index.tsOops! Something went wrong! :( ESLint: 8.57.1 ESLint couldn't find the plugin "eslint-plugin-vue". (The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:
The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue". If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. packages/utils/src/array/index.tsOops! Something went wrong! :( ESLint: 8.57.1 ESLint couldn't find the plugin "eslint-plugin-vue". (The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:
The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue". If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.
Tip ⚡🧪 Multi-step agentic review comment chat (experimental)
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
[e2e-test-warn] The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug". Please make sure you've read our contributing guide |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (17)
packages/utils/src/crypt/index.ts (4)
8-9
: Consider using type narrowing instead of type casting.While adding the
: ArrayBuffer
type annotation is good, the explicit type casting could be improved by using TypeScript's type narrowing.- const msgUint8: ArrayBuffer = isArrayBuffer ? (message as ArrayBuffer) : new TextEncoder().encode(message as string) // 编码为(utf-8)Uint8Array + const msgUint8: ArrayBuffer = isArrayBuffer ? message : new TextEncoder().encode(message as string) // 编码为(utf-8)Uint8Array
5-18
: Consider adding error handling.The function doesn't have any error handling for potential exceptions from the crypto API. Web Crypto operations can fail for various reasons like unsupported algorithms or insufficient permissions.
export async function sha256(message: ArrayBuffer | string): Promise<string> { // 判断输入是否为ArrayBuffer类型 const isArrayBuffer: boolean = Object.prototype.toString.call(message) === '[object ArrayBuffer]' // 编码为(utf-8)Uint8Array,确保输入符合BufferSource类型要求 const msgUint8: ArrayBuffer = isArrayBuffer ? (message as ArrayBuffer) : new TextEncoder().encode(message as string) // 编码为(utf-8)Uint8Array // 计算消息的哈希值 + try { const hashBuffer: ArrayBuffer = await globalThis.crypto.subtle.digest('SHA-256', msgUint8) // 将缓冲区转换为字节数组 const hashArray: number[] = Array.from(new Uint8Array(hashBuffer)) // 将字节数组转换为十六进制字符串 const hashHex: string = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('') return hashHex + } catch (error) { + console.error('SHA-256 hashing failed:', error) + throw new Error('Failed to generate SHA-256 hash') + } }
1-18
: Consider translating all comments to English.The code contains Chinese comments. For international maintainability, consider translating all comments to English to ensure consistency across the codebase.
- /** 生成字节流或字符串的sha256编码 + /** Generate SHA-256 hash of a byte stream or string - * @param message - 需要计算哈希值的消息(字符串或ArrayBuffer) + * @param message - The message to hash (string or ArrayBuffer) - * @returns 返回消息的SHA-256哈希值(十六进制字符串) + * @returns The SHA-256 hash of the message (hexadecimal string) */ export async function sha256(message: ArrayBuffer | string): Promise<string> { - // 判断输入是否为ArrayBuffer类型 + // Check if input is ArrayBuffer type const isArrayBuffer: boolean = Object.prototype.toString.call(message) === '[object ArrayBuffer]' - // 编码为(utf-8)Uint8Array,确保输入符合BufferSource类型要求 - const msgUint8: ArrayBuffer = isArrayBuffer ? (message as ArrayBuffer) : new TextEncoder().encode(message as string) // 编码为(utf-8)Uint8Array + // Encode as (UTF-8) Uint8Array, ensuring input meets BufferSource type requirements + const msgUint8: ArrayBuffer = isArrayBuffer ? (message as ArrayBuffer) : new TextEncoder().encode(message as string) - // 计算消息的哈希值 + // Compute the hash of the message const hashBuffer: ArrayBuffer = await globalThis.crypto.subtle.digest('SHA-256', msgUint8) - // 将缓冲区转换为字节数组 + // Convert buffer to byte array const hashArray: number[] = Array.from(new Uint8Array(hashBuffer)) - // 将字节数组转换为十六进制字符串 + // Convert byte array to hexadecimal string const hashHex: string = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('') return hashHex }
7-7
: Consider using TypeScript'sinstanceof
operator for type checking.The current type checking uses
Object.prototype.toString.call()
, which works but is less idiomatic in TypeScript. Consider using theinstanceof
operator for cleaner type checking.- const isArrayBuffer: boolean = Object.prototype.toString.call(message) === '[object ArrayBuffer]' + const isArrayBuffer: boolean = message instanceof ArrayBufferpackages/utils/src/debounce/__tests__/debounce.test.ts (1)
16-19
: Consider using a more specific type instead of extending FunctionThe
DebounceFunction
interface extends the genericFunction
type, which is discouraged in TypeScript as it's not type-safe. Instead, consider defining the function signature explicitly.-interface DebounceFunction extends Function { +interface DebounceFunction { + (...args: any[]): any; _cancel?: () => void }🧰 Tools
🪛 Biome (1.9.4)
[error] 18-18: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/debounce/index.ts (1)
15-20
: Consider using a more specific type instead of extending FunctionThe
DebounceFunction
interface extends the genericFunction
type, which is discouraged in TypeScript as it's not type-safe. Consider defining the function signature explicitly.-export interface DebounceFunction extends Function { +export interface DebounceFunction { + (...args: any[]): any; _cancel?: () => void }🧰 Tools
🪛 Biome (1.9.4)
[error] 19-19: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/date/__test__/index.test.ts (3)
39-45
: Straightforward test for theformat
function.The test verifies basic date formatting capabilities with different format patterns. Consider adding more complex format patterns to test edge cases.
it('应该正确格式化日期', () => { const date = new Date(2024, 2, 18, 12, 30, 45) expect(format(date, 'yyyy/MM/dd')).toBe('2024/03/18') expect(format(date, 'yyyy年MM月dd日')).toBe('2024年03月18日') + expect(format(date, 'yyyy-MM-dd hh:mm:ss')).toBe('2024-03-18 12:30:45') + expect(format(date, 'M/d/yy h:m')).toBe('3/18/24 12:30') })
55-60
: Simple verification of thetoDateStr
function.The test confirms basic date-to-string conversion works as expected. Consider adding a test case with the optional timezone parameter to ensure that functionality is also covered.
it('应该正确转换日期字符串', () => { const date = new Date(2024, 2, 18, 12, 30) expect(toDateStr(date, 'yyyy/MM/dd hh:mm')).toBe('2024/03/18 12:30') + // Test with timezone parameter + expect(toDateStr(date, 'yyyy/MM/dd hh:mm', 0)).toBe('2024/03/18 04:30') // Assuming local timezone is UTC+8 })
76-81
: Basic verification of thegetLocalTimezone
function.The test only checks the return type but not the actual value. Consider enhancing this test to verify that the returned timezone value is reasonable (e.g., within -12 to +14 range).
it('应该返回本地时区', () => { const timezone = getLocalTimezone() expect(typeof timezone).toBe('number') + expect(timezone).toBeGreaterThanOrEqual(-12) + expect(timezone).toBeLessThanOrEqual(14) })packages/utils/src/validate/validations/number.ts (1)
28-63
: Consider adding a function name for better stack traces.While the TypeScript annotations are excellent, the function is still anonymous. Consider giving it a name (like
numberValidation
) to improve error stack traces and make it easier to reference in documentation.-export default function ( +export default function numberValidation( rule: { required?: boolean field: string type?: string min?: number max?: number [key: string]: any }, checkValue: any, callback: (errors?: any[]) => void, source: Record<string, any>, options?: Record<string, any> ): void {🧰 Tools
🪛 Biome (1.9.4)
[error] 57-57: The function should not return a value because its return type is void.
The function is here:
'void' signals the absence of value. The returned value is likely to be ignored by the caller.
(lint/correctness/noVoidTypeReturn)
packages/utils/src/decimal/index.ts (1)
109-132
: Don't use 'Function' as a type in the interfaceThe
DecimalConstructor
interface usesFunction
as a type, which is discouraged because it accepts any function-like value and can lead to type safety issues.Consider replacing it with a more specific function type:
-interface DecimalConstructor extends Function { +interface DecimalConstructor { + new (num: number | string | IDecimal): IDecimal; (num: number | string | IDecimal): IDecimal add: (a: number | string | IDecimal, b: number | string | IDecimal) => IDecimal sub: (a: number | string | IDecimal, b: number | string | IDecimal) => IDecimal mul: (a: number | string | IDecimal, b: number | string | IDecimal) => IDecimal div: (a: number | string | IDecimal, b: number | string | IDecimal) => IDecimal }🧰 Tools
🪛 Biome (1.9.4)
[error] 130-130: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/dataset/index.ts (3)
197-213
: Consider using optional chaining for cleaner code.The current approach using logical OR is valid, but optional chaining would make the code more modern and readable.
- const { key = 'id', parentKey } = tree || {} + const key = tree?.key ?? 'id' + const parentKey = tree?.parentKey🧰 Tools
🪛 Biome (1.9.4)
[error] 203-203: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
227-229
: Consider improving the type assertion.The
as any
casting could potentially be replaced with a more specific type to maintain better type safety.- return resolve(transForm(dataset as any, tree)) + return resolve(transForm(dataset as unknown as ResponseData, tree))
278-280
: Consider using optional chaining in the promise chain.The promise chain could be simplified with optional chaining.
- .then((response: ResponseData) => { - resolve(transForm(response, tree)) - }) + .then((response: ResponseData) => resolve(transForm(response, tree)))packages/utils/src/bigInt/index.ts (2)
441-443
: Consider using optional chaining for better type safety.The
toNumber()
method is assumed to always exist, making this a good candidate for optional chaining.- negate(): NumberDecimal { - return new NumberDecimal(String(-this.toNumber())) + negate(): NumberDecimal { + return new NumberDecimal(String(-(this.toNumber() ?? 0)))🧰 Tools
🪛 Biome (1.9.4)
[error] 442-443: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
557-559
: Consider adding error handling for invalid inputs.The comparison function would benefit from handling invalid inputs to prevent potential runtime errors.
export function lessEquals(value1: string | number, value2: string | number): boolean { - return getMiniDecimal(value1, undefined).lessEquals(getMiniDecimal(value2, undefined)) + try { + return getMiniDecimal(value1, undefined).lessEquals(getMiniDecimal(value2, undefined)) + } catch (error) { + // Log the error and return a default value or rethrow based on requirements + console.error('Error comparing values:', error) + return false + } }packages/utils/src/validate/util.ts (1)
304-318
: Consider simplifying the type assertions in complementError.The multiple type assertions make the code harder to follow. Consider using more specific types or simplifying the logic.
export function complementError(rule: { fullField?: string [key: string]: any }): (onError: string | Function | { message?: string; field?: string }) => { message: string; field: string } { return (onError) => { - if (onError && (onError as any).message) { - ;(onError as any).field = (onError as any).field || rule.fullField - return onError as { message: string; field: string } + // Check if onError is an object with a message property + if (onError && typeof onError === 'object' && 'message' in onError) { + const errorObj = onError as { message: string; field?: string } + errorObj.field = errorObj.field || rule.fullField + return errorObj as { message: string; field: string } } return { - message: typeof onError === 'function' ? (onError as Function)() : String(onError), - field: (onError as any)?.field || rule.fullField + message: typeof onError === 'function' ? onError() : String(onError), + field: (typeof onError === 'object' && onError?.field) || rule.fullField } } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (44)
packages/utils/src/after-leave/__tests__/index.test.ts
(1 hunks)packages/utils/src/after-leave/index.ts
(2 hunks)packages/utils/src/array/__tests__/index.test.ts
(1 hunks)packages/utils/src/array/index.ts
(10 hunks)packages/utils/src/bigInt/__tests__/index.test.ts
(1 hunks)packages/utils/src/bigInt/index.ts
(11 hunks)packages/utils/src/calendar/__test__/index.test.ts
(1 hunks)packages/utils/src/calendar/index.ts
(5 hunks)packages/utils/src/common/__tests__/index.test.ts
(1 hunks)packages/utils/src/common/index.ts
(5 hunks)packages/utils/src/crypt/index.ts
(1 hunks)packages/utils/src/dataset/index.ts
(5 hunks)packages/utils/src/date/__test__/index.test.ts
(1 hunks)packages/utils/src/date/index.ts
(2 hunks)packages/utils/src/debounce/__tests__/debounce.test.ts
(1 hunks)packages/utils/src/debounce/index.ts
(1 hunks)packages/utils/src/decimal/__tests__/index.test.ts
(1 hunks)packages/utils/src/decimal/index.ts
(9 hunks)packages/utils/src/validate/__test__/util.test.ts
(1 hunks)packages/utils/src/validate/util.ts
(10 hunks)packages/utils/src/validate/validations/__test__/array.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/date.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/enum.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/float.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/integer.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/method.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/number.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/pattern.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/required.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/string.test.ts
(1 hunks)packages/utils/src/validate/validations/__test__/type.test.ts
(1 hunks)packages/utils/src/validate/validations/array.ts
(1 hunks)packages/utils/src/validate/validations/date.ts
(2 hunks)packages/utils/src/validate/validations/enum.ts
(1 hunks)packages/utils/src/validate/validations/float.ts
(1 hunks)packages/utils/src/validate/validations/integer.ts
(1 hunks)packages/utils/src/validate/validations/method.ts
(1 hunks)packages/utils/src/validate/validations/number.ts
(1 hunks)packages/utils/src/validate/validations/pattern.ts
(1 hunks)packages/utils/src/validate/validations/required.ts
(1 hunks)packages/utils/src/validate/validations/string.ts
(1 hunks)packages/utils/src/validate/validations/type.ts
(1 hunks)packages/utils/src/xss/__tests__/xss.test.ts
(1 hunks)packages/utils/vitest.config.ts
(1 hunks)
🧰 Additional context used
🧬 Code Definitions (17)
packages/utils/src/validate/validations/__test__/method.test.ts (1)
packages/utils/src/validate/validations/method.ts (1) (1)
validate
(41:64)
packages/utils/src/decimal/__tests__/index.test.ts (2)
packages/utils/src/decimal/index.ts (4) (4)
Decimal
(156:202)toFixed
(230:241)formatNumber
(332:352)recoverNumber
(360:373)packages/utils/src/bigInt/index.ts (1) (1)
toFixed
(578:613)
packages/utils/src/calendar/__test__/index.test.ts (1)
packages/utils/src/calendar/index.ts (7) (7)
getDays
(10:12)getWeek
(22:23)lastMonth
(32:45)nextMonth
(54:67)getCalendar
(100:138)transformArray
(146:163)parseDate
(183:195)
packages/utils/src/validate/validations/__test__/number.test.ts (1)
packages/utils/src/validate/util.ts (1) (1)
isEmptyValue
(129:143)
packages/utils/src/validate/validations/__test__/date.test.ts (1)
packages/utils/src/validate/validations/date.ts (1) (1)
dateValidator
(27:77)
packages/utils/src/date/__test__/index.test.ts (1)
packages/utils/src/date/index.ts (8) (8)
isLeapYear
(83:83)toDate
(361:376)format
(418:459)getDateWithNewTimezone
(473:484)toDateStr
(493:503)getWeekOfFirstDay
(517:531)getLocalTimezone
(535:535)getStrTimezone
(537:551)
packages/utils/src/validate/validations/__test__/string.test.ts (1)
packages/utils/src/validate/validations/string.ts (1) (1)
stringValidation
(28:73)
packages/utils/src/debounce/__tests__/debounce.test.ts (1)
packages/utils/src/debounce/index.ts (2) (2)
DebounceFunction
(18:20)debounce
(30:32)
packages/utils/src/validate/__test__/util.test.ts (1)
packages/utils/src/validate/util.ts (8) (8)
warning
(22:22)convertFieldsError
(29:45)format
(54:91)isEmptyValue
(129:143)isEmptyObject
(150:152)asyncMap
(240:297)complementError
(304:319)deepMerge
(327:346)
packages/utils/src/array/__tests__/index.test.ts (1)
packages/utils/src/array/index.ts (9) (9)
indexOf
(31:41)find
(53:56)remove
(71:80)sort
(93:111)push
(125:131)unique
(142:157)toObject
(181:191)transformPidToChildren
(205:235)transformTreeData
(245:262)
packages/utils/src/after-leave/__tests__/index.test.ts (1)
packages/utils/src/after-leave/index.ts (1) (1)
afterLeave
(35:67)
packages/utils/src/common/__tests__/index.test.ts (1)
packages/utils/src/common/index.ts (12) (12)
KEY_CODE
(17:111)POSITION
(117:117)SORT
(124:124)REFRESH_INTERVAL
(130:130)IPTHRESHOLD
(136:136)DATE
(142:151)DATEPICKER
(164:253)BROWSER_NAME
(259:264)MOUSEDELTA
(270:270)VALIDATE_STATE
(276:280)CASCADER
(286:310)version
(316:316)
packages/utils/src/validate/validations/__test__/array.test.ts (1)
packages/utils/src/validate/validations/array.ts (1) (1)
arrayValidation
(28:59)
packages/utils/src/bigInt/__tests__/index.test.ts (2)
packages/utils/src/bigInt/index.ts (15) (15)
supportBigInt
(19:21)trimNumber
(28:71)isE
(78:81)validateNumber
(88:103)getNumberPrecision
(112:127)num2str
(134:152)BigIntDecimal
(196:410)NumberDecimal
(415:541)setDecimalClass
(547:549)getMiniDecimal
(184:191)lessEquals
(369:371)lessEquals
(513:515)lessEquals
(557:559)equalsDecimal
(567:569)toFixed
(578:613)packages/utils/src/decimal/index.ts (1) (1)
toFixed
(230:241)
packages/utils/src/date/index.ts (2)
packages/utils/src/date-util/index.ts (2) (2)
isDate
(41:53)toDate
(55:55)packages/utils/src/type/index.ts (2) (2)
isDate
(150:150)isNumeric
(142:142)
packages/utils/src/validate/validations/__test__/pattern.test.ts (1)
packages/utils/src/validate/validations/pattern.ts (1) (1)
pattern
(28:59)
packages/utils/src/common/index.ts (1)
packages/utils/src/index.ts (12) (12)
KEY_CODE
(137:137)POSITION
(138:138)SORT
(139:139)REFRESH_INTERVAL
(140:140)IPTHRESHOLD
(141:141)DATE
(142:142)DATEPICKER
(143:143)BROWSER_NAME
(144:144)MOUSEDELTA
(145:145)VALIDATE_STATE
(146:146)CASCADER
(147:147)version
(148:148)
🪛 Biome (1.9.4)
packages/utils/src/after-leave/index.ts
[error] 45-47: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/debounce/index.ts
[error] 19-19: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/debounce/__tests__/debounce.test.ts
[error] 18-18: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/dataset/index.ts
[error] 203-203: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 257-258: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 280-281: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
packages/utils/src/decimal/index.ts
[error] 130-130: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
packages/utils/src/bigInt/index.ts
[error] 442-443: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
[error] 565-567: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
packages/utils/src/calendar/index.ts
[error] 181-183: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
⏰ Context from checks skipped due to timeout of 90000ms (8)
- GitHub Check: Dispatch All Test (1/8)
- GitHub Check: Dispatch All Test (4/8)
- GitHub Check: Dispatch All Test (6/8)
- GitHub Check: Dispatch All Test (8/8)
- GitHub Check: Dispatch All Test (2/8)
- GitHub Check: Dispatch All Test (5/8)
- GitHub Check: Dispatch All Test (7/8)
- GitHub Check: Dispatch All Test (3/8)
🔇 Additional comments (244)
packages/utils/src/crypt/index.ts (4)
1-4
: Well-documented JSDoc comment.The JSDoc comments provide clear documentation for the function's purpose, parameters, and return value. This significantly improves code maintainability and developer experience.
5-5
: Correct Promise return type annotation.Adding the explicit return type
Promise<string>
is a good TypeScript practice. It clearly documents the contract of this async function and helps with type checking.
6-7
: Type annotation enhances type safety.Adding the
: boolean
type annotation toisArrayBuffer
improves code readability and type safety.
10-15
: Clear type annotations for all variables.The explicit type annotations for
hashBuffer
,hashArray
, andhashHex
improve code clarity and type safety. The comments also clearly explain each step of the hashing process.packages/utils/vitest.config.ts (1)
1-13
: Well-structured Vitest configurationThe configuration is properly set up with appropriate test patterns and coverage settings. The include pattern correctly targets TypeScript test files in
__test__
directories, and the coverage configuration excludes test files and other non-source code.packages/utils/src/calendar/index.ts (9)
10-12
: Well-typed implementation of getDaysThe function signature has been properly typed with number parameters and return type, matching the JSDoc.
22-23
: Improved getWeek implementation with proper typesThe function now uses proper TypeScript typing and a concise arrow function implementation.
32-45
: Well-typed implementation of lastMonth with clear return typeThe function signature now correctly specifies the return type as an object with year and month properties.
54-67
: Well-typed implementation of nextMonth with clear return typeThe function signature now correctly specifies the return type as an object with year and month properties.
72-91
: Good addition of CalendarData interfaceThe newly added interface provides clear type definition for the calendar data structure, making the code more self-documenting and type-safe.
100-138
: Well-typed implementation of getCalendar with explicit return typeThe function now correctly uses the CalendarData interface as its return type, improving type safety.
146-163
: Improved transformArray with generic typeThe function now uses a generic type parameter to maintain type safety for arrays of any type, and properly declares the result as a two-dimensional array.
168-175
: Good addition of ParsedDate interfaceThe interface clearly defines the structure of parsed date objects, enhancing type safety and documentation.
183-195
: Well-typed implementation of parseDate with clear parameter and return typesThe function now accepts both number and string types for the time parameter and returns a well-defined ParsedDate object.
packages/utils/src/xss/__tests__/xss.test.ts (1)
8-8
:✅ Verification successful
Updated test expectation for filterHtml behavior
The test now expects the function to retain the
href
attribute but remove its value when encountering a JavaScript URL, rather than removing the attribute entirely.
🏁 Script executed:
#!/bin/bash # Check if the implementation of filterHtml has been updated to match this test expectation # Find the implementation of filterHtml rg -A 5 'filterHtml' --type ts --glob '!**/__test__/**' packages/utils/src/xssLength of output: 1954
Verified: Updated behavior for filterHtml is correctly implemented.
- The inline snapshot in
packages/utils/src/xss/__tests__/xss.test.ts
now expects<a href>Click Me</a>
, indicating that the function retains thehref
attribute while removing its value for JavaScript URLs.- The grep output confirms that the implementation of
filterHtml
is present and aligned with this expectation.packages/utils/src/validate/validations/__test__/method.test.ts (4)
1-13
: Good test for non-required empty fieldsThis test properly verifies that validation passes when a field is not required and its value is empty, which matches the expected behavior of the validate function.
15-23
: Good test for required empty fieldsThis test correctly verifies that validation fails when a field is required but its value is empty, ensuring the validate function properly enforces required fields.
25-33
: Good test for missing non-required fieldsThis test properly verifies that validation passes when a field is not in the source object and is not required, which is an important edge case to cover.
35-43
: Good test for non-required fields with valuesThis test correctly verifies that validation passes when a field is in the source object, has a value, and is not required.
packages/utils/src/debounce/__tests__/debounce.test.ts (1)
21-98
: Well-structured comprehensive test suite for debounce functionalityThe test suite thoroughly covers all essential scenarios for the debounce function:
- Delayed execution after the specified timeout
- Multiple calls resulting in a single execution
- Immediate execution with
atBegin: true
- Parameter handling when
atBegin
is a callback function- Cancellation via the
_cancel
methodThe tests use Vitest's timer mocks appropriately and verify both function calls and timing expectations, providing good coverage of the debounce functionality.
packages/utils/src/debounce/index.ts (2)
22-30
: Good JSDoc documentation with clear parameter and return type descriptionsThe JSDoc comments provide clear descriptions of the parameters and return type, which enhances code understandability and IDE auto-completion support.
30-30
: Excellent type annotations that improve type safetyAdding proper TypeScript type annotations to the debounce function enhances type checking and improves code maintainability and IDE support.
packages/utils/src/validate/validations/__test__/type.test.ts (2)
18-38
: Well-organized mock setup for clean testing isolationThe mocking approach effectively isolates the
typeValidation
function from its dependencies, making the tests more reliable and focused. The clear separation of mock setup from test cases improves readability.
40-143
: Comprehensive test cases covering key validation scenariosThe test suite thoroughly covers important validation scenarios:
- Empty values with non-required fields
- Non-empty values requiring type validation
- Missing fields that are non-required
- Required field validation
Each test follows a clear arrange-act-assert pattern with descriptive comments and appropriate expectations, ensuring the type validation logic is properly tested.
packages/utils/src/validate/validations/__test__/float.test.ts (2)
16-40
: Clean mock implementation with direct inline utility functionsThe mocking approach is well-structured, with explicit implementations that help clarify the expected behavior. The direct implementation of
isEmptyValue
is particularly useful for making the tests more readable and predictable.
42-172
: Thorough test coverage with edge cases and error handlingThis test suite provides excellent coverage of the float validation functionality:
- Empty values (both required and non-required)
- Valid float values
- Range validation
- Proper error propagation
- Undefined value handling
The tests clearly verify that each validation rule is called with the correct parameters and that errors are properly collected and passed to the callback function. This comprehensive approach ensures robust validation behavior.
packages/utils/src/validate/validations/__test__/required.test.ts (1)
1-104
: Well-structured and comprehensive test suite for required validation.This test file provides excellent coverage for the
required
validation function, testing various scenarios including empty strings, undefined, null, empty arrays, and non-empty values. The test cases are well-organized and clearly named, making the validation logic easy to understand and verify.I especially appreciate the thorough approach to testing both positive and negative cases, including checking error message propagation and handling of optional fields.
packages/utils/src/validate/validations/__test__/string.test.ts (4)
1-11
: Appropriate copyright headers included.The file correctly includes the necessary copyright and license information required for the project.
13-48
: Well-implemented dependency mocking strategy.Your approach to mocking dependencies (
rules
,isEmptyValue
, andhasOwn
) is excellent. This isolates thestringValidation
function for proper unit testing and ensures that tests are focused on the validation logic rather than dependent implementations.
50-54
: Good test setup with beforeEach.Using
beforeEach
to reset mocks between tests prevents test interference and ensures consistent starting conditions for each test case.
56-131
: Comprehensive test coverage for string validation scenarios.The test cases cover all key validation scenarios including:
- Empty values with non-required fields
- Empty values with required fields
- Non-empty values with type/range/pattern validations
- Whitespace validation
- Source object property checks
Each test has clear expectations that validate both the function behavior and the interaction with dependencies.
packages/utils/src/decimal/__tests__/index.test.ts (4)
4-52
: Thorough testing of Decimal arithmetic operations.The tests for addition, subtraction, multiplication, and division operations are comprehensive, testing both the static methods (
(Decimal as any).add
) and instance methods (new (Decimal as any)().add()
). Each operation is tested with values known to cause floating-point precision issues in JavaScript, ensuring the Decimal utility correctly handles these cases.
54-84
: Good edge case coverage for toFixed function.The tests for
toFixed
thoroughly verify formatting behavior with different decimal precisions. I particularly like the inclusion of tests for small values (0.0001) and negative small values (-0.0001) with varying precision levels, which are common edge cases for decimal formatting.
86-107
: Comprehensive testing of formatNumber options.These tests effectively verify that the
formatNumber
function handles various formatting options correctly, including:
- Basic formatting
- Decimal precision
- Thousands separators
- Prefix/suffix handling
- Zero-value display options
This ensures the formatting function behaves as expected in all common use cases.
109-125
: Complete validation of recoverNumber parsing functionality.The tests for
recoverNumber
properly verify that the function can correctly parse formatted number strings back into numeric values, handling prefixes, suffixes, group separators, and different decimal separators. This ensures round-trip consistency between formatting and parsing operations.packages/utils/src/validate/validations/integer.ts (3)
17-31
: Clear and comprehensive JSDoc documentation.The added JSDoc comment provides excellent documentation for the integer validation function. It clearly describes the purpose, parameters, and the validation flow, making it much easier for developers to understand how to use this function properly.
32-45
: Improved type safety with TypeScript type annotations.The addition of explicit TypeScript types for the function parameters enhances type safety and IDE support. The detailed typing of the
rule
object with optional properties and an index signature provides good flexibility while maintaining type checking.
46-46
: Added explicit typing for the errors array.Explicitly typing the
errors
array asany[]
improves type safety and consistency with the function's TypeScript signature.packages/utils/src/after-leave/index.ts (4)
15-17
: LGTM! Clear documentation for event constant.Good addition of JSDoc comments to explain the purpose of the constant.
20-34
: Well-documented function with comprehensive JSDoc.The JSDoc comments clearly explain the purpose, parameters, and behavior of the function, making it easier for other developers to understand and use it correctly.
47-47
: Good addition of return type for the callback function.Adding explicit void return type to the eventCallback function improves type safety.
🧰 Tools
🪛 Biome (1.9.4)
[error] 45-47: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
65-65
: Helpful comment explaining the timeout mechanism.The comment clearly explains the fallback mechanism that ensures the callback is executed even if the transition event doesn't trigger.
packages/utils/src/calendar/__test__/index.test.ts (7)
1-18
: Great test coverage for getDays function.The tests effectively verify the function's behavior for regular months and leap years, providing good test coverage.
19-28
: Well-structured tests with clear expectations for getWeek function.Tests include clear comments explaining the expected results, which makes it easier to understand the behavior being verified.
30-46
: Comprehensive tests for lastMonth function including edge cases.Good job testing both the year rollover case and handling of numeric parameters. The test includes clear comments explaining the logic.
48-64
: Well-structured tests for nextMonth function covering all scenarios.Tests cover all relevant cases including year transitions. Good practice to include parameter type handling tests.
66-92
: Thorough test coverage for getCalendar function with edge case handling.The tests verify all aspects of the calendar data structure, including proper validation of current, previous, and next month data. Good job testing error cases with invalid parameters.
94-113
: Effective tests for transformArray function covering different input types.The tests verify the function's behavior with numeric arrays, string arrays, and the edge case of an empty array, ensuring all code paths are exercised.
115-137
: Complete test coverage for parseDate function including error handling.Tests verify both valid timestamp parsing and graceful handling of invalid inputs, ensuring the function's robustness.
packages/utils/src/validate/validations/float.ts (3)
17-26
: Excellent documentation with comprehensive JSDoc comments.The JSDoc comments clearly explain the purpose of the function, its parameters, and expected behavior, making it easier for other developers to understand and use it correctly.
27-40
: Well-structured TypeScript type definitions enhance function signature.The detailed type definitions for the function parameters improve type safety and make the API more explicit. Good job using generic types like
Record<string, any>
for flexible parameters while maintaining type checks.
41-41
: Good explicit typing of the errors array.Adding explicit type annotation for the errors array improves code clarity and type safety.
packages/utils/src/validate/validations/__test__/number.test.ts (9)
1-12
: Well-formatted copyright header and appropriate use of Vitest imports.The file includes the standard copyright header and properly imports the necessary testing utilities from Vitest.
13-31
: Good use of mocking to isolate tests from dependencies.The test properly mocks external dependencies (rules and isEmptyValue) to create isolated unit tests that aren't affected by the implementation of those dependencies.
33-39
: Effective test setup with proper mock reset.Using beforeEach to reset mocks between tests prevents test contamination and ensures each test runs in isolation.
41-54
: Good test for empty string handling.This test verifies that empty strings are properly converted to undefined before validation, which is an important edge case.
56-68
: Well-structured test for optional field validation.This test ensures that non-required fields with empty values bypass additional validation, which is a key validation behavior.
70-97
: Thorough test for required field validation with error handling.The test mocks the required rule to inject an error and verifies that the error is properly propagated through the callback. This ensures validation errors are correctly reported.
99-110
: Good test for conditional validation based on source object.This test verifies that validation is skipped when the field doesn't exist in the source object and isn't required, correctly implementing the validation contract.
112-123
: Effective test for range validation.This test ensures that both type and range validations are called when appropriate, verifying the core validation functionality.
125-136
: Good edge case test for undefined values.This test verifies the specific behavior when the value is undefined, ensuring that only required checks are performed and type/range validations are skipped.
packages/utils/src/validate/validations/required.ts (2)
15-26
: Well-documented JSDoc comments added!The JSDoc comments are comprehensive and provide clear descriptions of the function's purpose and parameters in both English and Chinese. This significantly improves code readability and maintainability.
27-35
: Good addition of TypeScript type annotationsThe explicit type annotations for parameters and return type enhance type safety and developer experience. The types are appropriately chosen:
rule
asRecord<string, any>
for the validation rule objectcallback
with proper function signature showing it accepts an array of errorscheckValue
asany
since it can be of various types- Explicit
void
return typepackages/utils/src/validate/validations/__test__/date.test.ts (9)
13-24
: Good test setup with proper mockingThe test properly imports the necessary testing utilities and mocks the rules module. This approach keeps the tests focused on the dateValidator function's behavior without being affected by the actual implementation of the rules.
25-29
: Proper test fixture managementUsing
afterEach
to reset mocks ensures each test starts with a clean state, which helps prevent test interdependencies and makes the tests more reliable.
31-40
: Comprehensive test for empty value handlingThis test correctly verifies that the validator skips validation and directly calls the callback when dealing with empty non-required values. The assertions are precise and validate both the positive (callback called) and negative (required rule not called) behaviors.
42-51
: Good coverage of required field validationThe test properly verifies that the required rule is invoked when the field is required but empty. This is a critical validation scenario.
53-64
: Thorough testing of date string handlingThe test effectively verifies how the validator processes valid date strings, confirming that both type and range validations are applied correctly. The assertions use
expect.any()
appropriately to check function calls with complex objects.
66-77
: Good test for timestamp handlingThe test correctly verifies that numeric timestamps are properly handled as valid date inputs. The test includes a comment explaining what the timestamp represents, which enhances readability.
79-91
: Complete testing of Date object handlingThe test thoroughly validates that the function correctly processes native Date objects, including proper verification of both type and range rule invocations with the expected parameters.
93-102
: Effective validation of field absence handlingThis test correctly verifies the validator's behavior when the field is absent from the source object, ensuring appropriate validation skipping for non-required fields.
104-120
: Comprehensive test for date range validationThe test effectively verifies date range validation by creating a scenario with specific min and max date values. It demonstrates a real-world use case and ensures the range rule is called with the correct timestamp value.
packages/utils/src/after-leave/__tests__/index.test.ts (7)
4-12
: Well-structured test environment setupGood test organization with proper setup and teardown. Using
useFakeTimers()
inbeforeEach
andrestoreAllMocks()
inafterEach
ensures tests run in isolation with controlled timing.
14-26
: Thorough error handling testThe test effectively verifies error handling for both missing instance and callback parameters. Using
@ts-expect-error
appropriately marks intentional type errors for testing purposes.
28-40
: Good test for default event registration behaviorThis test effectively verifies that
$on
is used by default for event registration and that$once
is not called, demonstrating complete verification of the expected behavior.
42-54
: Complete test for optional parameter behaviorThis test correctly verifies the behavior when the
once
parameter is set to true, ensuring$once
is used instead of$on
. The assertions check both the positive and negative expectations.
56-70
: Effective timing functionality testThe test properly verifies the timeout functionality using
advanceTimersByTime()
to simulate the passage of time. It checks that the callback is not called immediately but is triggered after the expected delay.
72-90
: Good test for callback execution guaranteeThis test effectively verifies that the event callback is executed only once, even if triggered multiple times, which is a critical aspect of the function's behavior.
92-111
: Complete test for parameter passingThe test thoroughly verifies that parameters are correctly passed to the callback function when the event is triggered, ensuring proper argument handling.
packages/utils/src/validate/validations/__test__/enum.test.ts (8)
13-31
: Good mocking setup with clear structureThe mock setup is well-structured, with clear separation between mock creation and use. Directly exposing mock functions as a local
rules
object improves test readability.
33-43
: Thorough utility function mockingThe test correctly mocks utility functions like
isEmptyValue
andhasOwn.call
to isolate the validation function under test from its dependencies. The mocks provide simplified implementations that match the expected behavior.
45-48
: Proper test state managementUsing
beforeEach
withclearAllMocks()
ensures each test starts with a clean state, preventing test interdependencies.
50-60
: Effective empty value handling testThis test correctly verifies that the validator skips validation and directly calls the callback when dealing with empty non-required values. The assertions check both function calls and the absence of validation rule invocations.
62-78
: Good required field validation testThe test correctly verifies that only the required rule is invoked (and not the enum rule) when the field is required but the value is empty. It checks the exact parameters passed to the required function.
80-97
: Complete enum validation testThis test thoroughly verifies that both required and enum rules are invoked with the correct parameters when a non-empty value is provided. The assertions are precise and check the exact arguments.
99-110
: Proper test for field absence handlingThe test correctly verifies the validator's behavior when the field is absent from the source object, ensuring that validation is skipped for non-required fields not present in the source.
112-135
: Thorough error propagation testThis test effectively verifies that errors from both the required and enum validations are collected and passed to the callback. The mock implementations are well-defined to simulate error generation, and the assertions check the exact error structure.
packages/utils/src/date/__test__/index.test.ts (6)
1-11
: Well-structured imports and organization.The imports are clean and correctly reference both Vitest testing utilities and the date utility functions from the parent directory. Good practice to import exactly what's needed.
13-21
: Well-organized test structure with clear descriptions.Using nested
describe
blocks provides a clear hierarchy of test organization. The test forisLeapYear
correctly validates both leap years (2000, 2020) and non-leap years (2100, 2023), providing good coverage for this utility function.
23-37
: Comprehensive testing of thetoDate
function.The tests verify both basic date parsing functionality and handling of different date formats. The comment on line 28 helpfully notes that months are zero-indexed in JavaScript Date objects, which might prevent confusion for future developers reading this test.
47-53
: Clear test for timezone conversion.The test verifies that a date can be correctly converted between timezones (from UTC+8 to UTC+0). This is an important functionality to test since timezone handling is often a source of bugs.
62-74
: Good test coverage forgetWeekOfFirstDay
.The tests verify both default behavior (where Monday is the first day of the week) and the optional parameter to use Sunday as the first day. This is comprehensive and checks the function's flexibility.
83-93
: Thorough tests forgetStrTimezone
.The tests cover string and number format timezone parsing, which ensures the function handles different input types correctly.
packages/utils/src/validate/validations/__test__/integer.test.ts (8)
1-12
: Well-formatted copyright notice.The copyright notice is comprehensive and correctly follows the project's license format.
13-26
: Well-organized test setup with proper mocking.The imports and mocking setup are clear, using Vitest's mocking utilities to isolate the integer validation function from its dependencies.
28-45
: Clear test for empty value with non-required rule.The test verifies that validation is skipped when the value is empty and the rule is not required, which is an important base case.
47-58
: Effective test for undefined value with non-required rule.Similar to the previous test, this confirms that undefined values also bypass validation when not required.
60-72
: Well-structured test for required rule validation.The test verifies that when a rule is marked as required, the appropriate validation functions are called in sequence, which is crucial for the validation flow.
74-86
: Comprehensive test for type and range validation.This test ensures that both type and range validations are performed when a value is present, with proper parameters being passed to each validation function.
88-99
: Good edge case test for field absence in source object.This test verifies the behavior when the field doesn't exist in the source object, which is an important edge case to handle.
101-115
: Thorough test for error callback mechanism.The test mocks the required validation to inject an error and verifies that errors are correctly passed to the callback function, which is essential for the validation error reporting flow.
packages/utils/src/validate/validations/__test__/array.test.ts (8)
1-12
: Consistent copyright notice format.The copyright notice follows the same format as other files, maintaining consistency across the codebase.
13-34
: Well-structured test setup with effective mocking.The test setup includes clear mocking of dependencies and a custom implementation of
isEmptyValue
to control test behavior. ThebeforeEach
hook ensures test isolation by clearing mocks between tests.
36-43
: Comprehensive mock implementation forisEmptyValue
.The mock implementation correctly handles array emptiness checks, which is crucial for testing the array validation function.
45-61
: Clear test for empty array with non-required rule.The test verifies that validation is bypassed when the array is empty and not required, which is an important base case for array validation.
63-81
: Thorough test for required validation of empty arrays.This test ensures that required validation is performed on empty arrays when the rule specifies it as required, with proper parameters being passed to the validation function.
83-102
: Comprehensive test for non-empty array validation.The test verifies that both type and range validations are performed on non-empty arrays, with the correct parameters being passed to each validation function.
104-116
: Good edge case test for field absence.This test ensures correct behavior when the field is not present in the source object, which is an important edge case to handle in validation scenarios.
118-133
: Effective test for error callback mechanism.The test demonstrates that errors are correctly gathered and passed to the callback function, which is essential for the validation error reporting flow.
packages/utils/src/validate/validations/number.ts (3)
17-27
: Excellent JSDoc documentation added.The newly added JSDoc comments provide comprehensive information about the function's purpose, parameters, and return type, significantly improving code documentation and maintainability.
28-41
: Enhanced type safety with TypeScript annotations.The function signature has been enhanced with detailed TypeScript type annotations, improving type safety and helping catch potential errors at compile time. The structured type definition for the rule object is particularly helpful.
42-42
: Type annotation for errors array.Adding the type annotation for the errors array completes the TypeScript conversion of this function, ensuring consistent typing throughout.
packages/utils/src/validate/validations/type.ts (3)
17-27
: Great JSDoc documentation!The detailed JSDoc comments clearly explain the function's purpose, parameters, and usage. This significantly improves code readability and maintainability.
28-39
: Well-defined TypeScript type annotations.The explicit type definitions for the function parameters significantly enhance type safety. The rule object's structure is clearly defined with required and optional properties, making it easier for developers to understand what inputs are expected.
41-41
: Good explicit typing of local variables.Adding the explicit type annotation for the
errors
array improves code clarity and consistency with the rest of the function's typing approach.packages/utils/src/common/__tests__/index.test.ts (13)
1-15
: Well-structured imports and appropriate testing framework setup.The imports are properly organized and the Vitest testing framework is correctly set up. All necessary constants from the common index module are imported for testing.
17-27
: Comprehensive keyboard key code tests.The test suite properly validates that the KEY_CODE constants match their expected values, providing good coverage of different key types.
29-36
: Position constant validation is thorough.All position constants (Left, Right, Top, Bottom) are correctly tested against their expected string values.
38-43
: Sort direction constants are properly tested.The test correctly verifies the ascending and descending sort constants.
45-49
: Refresh interval constant validation.The test successfully verifies that the REFRESH_INTERVAL constant is correctly set to 100.
51-57
: IP threshold constants validation is complete.All IP threshold constants (Min, Max, NonNumeric) are correctly tested against their expected values.
59-66
: Date format constants are well tested.The test suite properly validates that the DATE constants match their expected format strings.
68-89
: Comprehensive DATEPICKER constant tests.The test suite provides thorough coverage of the DATEPICKER constants, including basic formats, date format mappings, and lists for weeks and months.
91-98
: Browser name constants validation is complete.All browser name constants are correctly tested against their expected string values.
100-104
: Mouse delta constant validation is correct.The test successfully verifies that the MOUSEDELTA constant is set to 120.
106-112
: Validation state constants are well tested.All validation state constants (Validating, Success, Error) are correctly tested against their expected string values.
114-130
: CASCADER constant tests are thorough.The test suite provides comprehensive coverage of the CASCADER constants, including selectors, property mappings, and event mappings.
132-137
: Version constant test is correctly implemented.The test properly verifies that the version constant matches the environment variable.
packages/utils/src/validate/validations/date.ts (5)
17-26
: Excellent JSDoc documentation.The detailed JSDoc comments clearly explain the function's purpose, parameters, and usage. This significantly improves code readability and maintainability.
27-40
: Good function naming and well-defined TypeScript type annotations.Naming the function
dateValidator
improves code readability and searchability. The explicit type definitions for parameters significantly enhance type safety, particularly the structured rule object with optional properties.
41-42
: Proper typing of local variables.Adding explicit type annotations for the
errors
array andvalidate
boolean improves code clarity and consistency.
44-50
: Well-documented helper function.The JSDoc comment for
isValidDateStr
clearly explains its purpose and parameters, and the function is properly typed with parameter and return type annotations.
60-60
: Good explicit typing of the date object.Adding the explicit type annotation for the
dateObject
variable improves code clarity and helps prevent potential type-related bugs.packages/utils/src/validate/validations/enum.ts (3)
19-28
: Comprehensive JSDoc documentation.The JSDoc comments clearly explain the function's purpose, parameters, and usage, which significantly improves code readability and maintainability.
29-43
: Well-structured TypeScript type annotations.The explicit type definitions for the function parameters significantly enhance type safety. The rule object structure is clearly defined with required and optional properties, and the options object has a nested structure that accurately represents its usage.
44-45
: Proper typing of local variables.Adding explicit type annotations for the
errors
array andvalidate
boolean improves code clarity and consistency with the rest of the TypeScript implementation.packages/utils/src/validate/validations/array.ts (3)
17-27
: Well-structured JSDoc comment with clear description.The JSDoc comment provides comprehensive documentation of the function's purpose, parameters, and return type. This improves code readability and makes it easier for developers to understand how to use this function.
28-41
: Good TypeScript interface definition with proper typing.The function signature has been properly typed with TypeScript, defining clear parameter types:
- The rule object is well-defined with optional properties and proper types
- The callback function type signature is correctly defined
- Using Record<string, any> for source and options parameters provides appropriate flexibility
This enhances type safety and improves IDE auto-completion support for developers using this function.
42-42
: Proper type annotation for the errors array.The explicit typing of the errors array as
any[]
ensures type consistency throughout the function.packages/utils/src/validate/validations/string.ts (3)
17-27
: Comprehensive JSDoc comment with detailed description.The JSDoc comment clearly explains the string validation function's purpose, parameters, and return value. It provides good context about the types of validations supported (required, type, range, pattern, and whitespace).
28-43
: Well-structured function signature with proper TypeScript types.The function signature has been properly typed with TypeScript:
- The rule object has appropriate optional properties with specific types (RegExp | string for pattern)
- The callback function type is correctly defined
- Using Record<string, any> for source and options provides the right level of flexibility
This enhances type safety and developer experience through improved IDE support.
44-44
: Proper type annotation for the errors array.The explicit typing of the errors array as
any[]
maintains type consistency throughout the function.packages/utils/src/validate/validations/pattern.ts (3)
17-27
: Clear and descriptive JSDoc comment.The JSDoc comment effectively communicates the function's purpose, parameters, and return type. This improves code maintainability and developer understanding.
28-42
: Detailed TypeScript function signature with appropriate types.The function signature has been well-structured with TypeScript types:
- The rule object properly defines field as required and pattern as optional with RegExp | string type
- The options object has been given a more specific structure with a required messages property
- The callback function type is correctly defined
This significantly improves type safety and makes the function's expected inputs clearer.
43-43
: Proper type annotation for the errors array.The explicit typing of the errors array as
any[]
ensures type consistency throughout the function.packages/utils/src/array/__tests__/index.test.ts (10)
1-6
: Good test setup with clear imports.The file starts with appropriate imports from Vitest and correctly imports all the array utility functions being tested.
7-29
: Comprehensive tests for indexOf function.The test suite for indexOf covers important scenarios:
- Finding elements in standard arrays
- Handling NaN values correctly (which is notoriously difficult in JavaScript)
- Returning -1 for non-existent elements
- Supporting custom assertion functions for complex objects
These tests thoroughly validate the function's behavior across edge cases.
31-43
: Thorough tests for find function.The tests for the find function properly verify:
- Finding elements based on a predicate function
- Returning undefined when no matching element is found
This ensures that the function meets its expected behavior.
45-69
: Comprehensive tests for remove function.The test cases for the remove function cover:
- Removing a single element from an array
- Removing multiple elements at once (using count parameter)
- Properly handling NaN values
- No changes when the element doesn't exist
These tests ensure the function behaves correctly in various scenarios.
71-89
: Well-structured tests for sort function.The sort function tests verify:
- Ascending order sorting by a field
- Descending order sorting by a field
- Proper handling of NaN values in sorting
These tests effectively validate the sort functionality.
91-109
: Effective tests for push function.The test cases for push function verify:
- Adding new elements to an array
- Not adding duplicates
- Correctly handling NaN values (which is a special case in JavaScript)
These tests comprehensively cover the function's behavior.
111-123
: Good coverage for unique function.The test cases properly verify:
- Removing duplicate elements from an array
- Handling NaN values correctly
This ensures the function works as expected with both regular values and special cases.
125-137
: Clear tests for toObject function.The tests for toObject validate:
- Converting an array of objects to a single object
- Properly handling field overrides (later fields override earlier ones)
These tests effectively verify the function's behavior.
139-169
: Thorough tests for transformPidToChildren function.The test suite verifies:
- Converting flat data to a tree structure
- Supporting custom field names for ID, parent ID, and children
These tests ensure the function's flexibility and correctness.
171-212
: Comprehensive tests for transformTreeData function.The test cases verify:
- Converting flat data to a tree structure
- Handling non-array inputs (single objects)
- Supporting custom field names
These tests provide good coverage of the function's capabilities.
packages/utils/src/validate/__test__/util.test.ts (10)
1-15
: Great test setup with proper imports and mocking!The imports are well organized and the code correctly imports all necessary functions from the util module. Good use of Vitest's test framework.
17-22
: Effective mocking of logger for clean test isolationUsing vi.mock to replace the logger's error function with a mock implementation helps isolate tests and allows for verifying error logging behavior without side effects.
24-29
: Proper test for the warning functionSimple and effective test for the warning function, verifying its expected behavior.
31-53
: Comprehensive tests for convertFieldsErrorGood coverage of both empty input handling and error grouping functionality. The test cases verify that:
null
,[]
, andundefined
inputs returnnull
- Errors are correctly grouped by field name when provided
The assertions are clear and verify the expected behavior.
55-85
: Thorough testing of format function with various input typesExcellent test coverage for the format function, including:
- Function input handling
- Various placeholder replacements (%s, %d, %j)
- Edge cases like insufficient replacement values
- Proper handling of %% escape sequence
- Non-string/non-function input handling
The tests are well structured and verify all key scenarios.
87-109
: Complete test coverage for isEmptyValueGood test cases for the isEmptyValue function, covering:
- null/undefined detection
- Empty array detection with proper type specification
- Empty string detection with different string types
- Non-empty values that should return false
The tests clearly verify the expected behavior in all scenarios.
111-116
: Clear isEmptyObject validation testsSimple and effective tests for the isEmptyObject function, verifying empty and non-empty object detection.
118-187
: Complex asyncMap testing with serial and parallel processingComprehensive testing of the asyncMap function, covering:
- Serial processing with option.first=true
- All fields processing with option.firstFields=true
- Specific fields processing with option.firstFields array
- Error handling and logger interaction
The test case on lines 175-186 effectively validates that errors during processing trigger logger.error calls.
189-224
: Detailed complementError tests for various error typesGood test coverage for the complementError function with different error types:
- Error objects with existing message property
- Error functions that return messages
- String error messages
Each test verifies both the message content and field assignment.
226-254
: Thorough testing of deepMerge functionalityThe tests cover all key aspects of the deepMerge function:
- Handling null sources
- Deep object merging with nested properties
- Value overwriting behavior
The assertions confirm that objects are merged correctly while maintaining their structure.
packages/utils/src/validate/validations/method.ts (4)
17-31
: Well-defined TypeScript interfaces improve type safetyThe addition of these interfaces provides clear type definitions for the validation function parameters:
ValidationRule
properly defines the expected structure of rule objectsValidationSource
andValidationOptions
clearly indicate the expected shapeValidationCallback
properly defines the callback signature with error arrayThis improves code readability and static type checking.
33-47
: Excellent JSDoc comments and improved function signatureThe detailed JSDoc comments provide clear documentation for the function's purpose and parameters in both English and Chinese. The updated function signature with proper type annotations enhances type safety and code maintainability.
49-49
: Properly typed errors variableThe explicit type annotation for the errors array improves code clarity and type safety.
52-54
: Better callback handling for empty valuesThe change to explicitly pass an empty array (
[]
) instead of no arguments ensures consistent behavior of the callback function, making the code more predictable and maintainable.packages/utils/src/bigInt/__tests__/index.test.ts (12)
1-17
: Well-structured imports and test setupThe imports are properly organized, importing all necessary functions and classes from the bigInt module for testing.
18-25
: Basic supportBigInt functionality testGood basic test to verify the supportBigInt function returns a boolean value as expected.
27-69
: Comprehensive trimNumber testsExcellent test coverage for the trimNumber function, including various scenarios:
- Integer handling
- Negative number handling
- Decimal number processing
- Trailing zeros removal
- Leading zeros removal
- Zero value handling
Each test case is well-described and validates specific trimming behavior.
87-109
: Thorough validateNumber testsGood coverage of validateNumber function behavior with:
- Valid number formats (integer, decimal, negative)
- Invalid input handling (empty string, null, undefined)
- Invalid format rejection
The tests verify all expected validation scenarios.
111-124
: Complete getNumberPrecision testsGood tests for number precision calculation, covering:
- Regular decimal numbers with different precision levels
- Scientific notation with different exponents
- Edge cases for precision calculation
The tests properly verify the precision detection logic.
126-141
: Effective num2str conversion testsGood test coverage for number-to-string conversion, including:
- Regular number formats
- Scientific notation handling
- Edge cases handling
The comment on lines 136-138 acknowledges potential floating-point precision issues, which is good practice.
143-191
: Conditional BigIntDecimal tests based on environment supportExcellent approach to testing the BigIntDecimal class with a conditional structure that:
- Only runs the detailed tests when BigInt is supported
- Provides a fallback test when BigInt is not supported
The tests cover instance creation, empty/invalid value handling, arithmetic operations, and comparison operations, ensuring comprehensive validation of the class functionality.
193-229
: Complete NumberDecimal class testsGood test coverage for the NumberDecimal class, mirroring most of the BigIntDecimal tests:
- Instance creation and validation
- Empty value handling
- Addition operations
- Negation operations
- Comparison operations
The tests provide comprehensive validation of the class's core functionality.
231-240
: Indirect testing of setDecimalClassGood approach to testing setDecimalClass by verifying its effect on getMiniDecimal. The comment on line 235-236 acknowledges the indirect nature of this test, which is appropriate when testing implementation details.
242-258
: Utility functions tests for comparisonsGood tests for the lessEquals and equalsDecimal utility functions, covering:
- Less than comparison
- Greater than comparison
- Equal value comparison
- String representation equality
These tests verify the correct behavior of the comparison utilities.
260-282
: Comprehensive toFixed testsExcellent test coverage for the toFixed function, including:
- Different precision levels
- Rounding behavior
- Empty string handling
- Negative number formatting
- Custom rounding rules
The tests on lines 277-281 for custom rounding rules are particularly thorough, testing both non-rounding and rounding scenarios.
72-85
:✅ Verification successful
Good isE function tests
Proper tests for the isE function that verify:
- Recognition of scientific notation in string format
- Proper handling of non-scientific numbers
The tests on line 77 may have a subtle issue - when testing
isE(1e5)
it expectsfalse
, but the function may returntrue
depending on implementation. Check if this is intended behavior.Run the following script to verify the behavior of the isE function with numeric literals:
🏁 Script executed:
#!/bin/bash # Print the implementation of the isE function echo "isE implementation:" rg -l "export function isE" packages/utils/src | xargs cat # Create a test file to check actual behavior echo "Testing actual behavior:" cat > test-ise.js << 'EOF' // Import the isE function if possible - may need adaptation depending on module system const isE = (number) => { let str = String(number); return !isNaN(Number(str)) && str.includes('e'); }; console.log("isE('1e5'):", isE('1e5')); console.log("isE(1e5):", isE(1e5)); console.log("String(1e5):", String(1e5)); console.log("String(1e5).includes('e'):", String(1e5).includes('e')); EOF node test-ise.jsLength of output: 22393
Confirmed behavior of isE tests for numeric literals
The tests correctly verify that the function returns
true
for scientific notation strings (e.g.,'1e5'
and'1e-5'
) and returnsfalse
for numeric literals (e.g.,1e5
), since converting the numeric literal to a string produces"100000"
without the scientific notation. No changes are required.packages/utils/src/validate/validations/__test__/pattern.test.ts (8)
1-3
: Proper test imports and setupCorrectly imports the necessary testing utilities from Vitest and the pattern function for testing.
4-15
: Good test for non-required empty fieldsThis test correctly verifies that the pattern validation passes when a field is not required and the value is empty, ensuring that optional fields can be left blank without triggering validation errors.
17-26
: Proper required field validation testGood test that confirms an error is returned when a field is required but the value is empty, validating the required field functionality within the pattern validation.
28-39
: Effective RegExp pattern mismatch testThis test properly validates that the pattern function returns an error when a value doesn't match the specified RegExp pattern. Good verification of both the error presence and the correct error message format.
41-51
: Good RegExp pattern match testCorrectly verifies that the pattern validation passes when a value matches the specified RegExp pattern.
53-64
: String pattern mismatch testProperly tests that the pattern function returns an error when a value doesn't match a pattern specified as a string. Good verification of the error message format with string patterns.
66-76
: String pattern match testCorrectly verifies that pattern validation passes when a value matches a pattern specified as a string.
78-88
: Field not in source testGood test that verifies pattern validation passes when a field is not in the source object and is not required, validating the proper handling of missing optional fields.
packages/utils/src/date/index.ts (7)
378-389
: Well-structured interface for date componentsAdding the
DateData
interface improves type safety and provides clear documentation for date-related operations. This makes the code more maintainable and self-documenting.
394-396
: Good type definition for format regex mappingThe
DateFormatRegs
interface properly types the regex mapping object, enhancing type safety when accessing format patterns.
401-409
: Clear interface for maximum date valuesThe
MaxDateValues
interface properly documents the maximum values for date components, improving code readability and type safety.
411-418
: Comprehensive JSDoc for format functionThe detailed JSDoc comments with parameter and return type annotations significantly improve documentation, making the function's purpose and usage clearer.
418-431
: Improved type safety in format functionThe explicit typing of parameters and return values improves type safety. Using
Record<string, number | string>
for the objecto
ensures proper type checking when accessing its properties.
445-455
: Better variable naming and argument handlingReplacing direct access to
arguments[2]
with the named variableactualAfterFormat
improves code readability and maintainability.
487-500
: Enhanced type safety in toDateStr functionThe proper type annotations for parameters and return values, along with explicit handling of timezone parsing and date object conversions, make the function more robust.
packages/utils/src/common/index.ts (10)
13-111
: Well-documented key code constants with proper typingThe addition of TypeScript typing (
Record<string, number>
) and comprehensive JSDoc comments for KEY_CODE constants improves type safety and documentation. This makes it clearer what each constant represents and ensures proper type checking when accessing these values.
113-117
: Properly typed position constantsAdding the
Record<string, string>
type to POSITION constants ensures type safety when accessing these values throughout the codebase.
119-124
: Good documentation for SORT constants with deprecation noticeThe addition of TypeScript typing along with a notice that this constant is pending removal is excellent documentation for future maintainers.
132-136
: Properly typed IP threshold constantsAdding the
Record<string, number>
type to IPTHRESHOLD constants ensures type safety when accessing these values.
138-151
: Well-typed date format constantsThe addition of TypeScript typing for DATE constants improves type safety when accessing these predefined date formats.
153-253
: Comprehensive typing for date picker constantsThe addition of TypeScript typing for DATEPICKER constants, though using
Record<string, any>
for flexibility, improves the overall type safety of the library.
255-264
: Properly typed browser name constantsAdding the
Record<string, string>
type to BROWSER_NAME constants ensures type safety when accessing these values.
272-280
: Well-typed validation state constantsAdding the
Record<string, string>
type to VALIDATE_STATE constants ensures type safety when accessing these validation states.
282-310
: Comprehensive typing for cascader constantsThe addition of TypeScript typing for CASCADER constants improves the overall type safety of the library when using cascader components.
312-316
: Properly typed version constantAdding the
string | undefined
type to the version constant clarifies that this value might be undefined in certain environments.packages/utils/src/decimal/index.ts (12)
20-48
: Improved type safety for asInteger functionAdding TypeScript type annotations to the
asInteger
function improves type safety and makes the function's purpose clearer.
50-66
: Simplified zero function with proper typingThe
zero
function has been improved with proper type annotations and simplified by usingString.prototype.repeat
directly.
68-91
: Well-typed negExp functionAdding TypeScript type annotations to the
negExp
function improves type safety and makes the function's purpose clearer.
93-108
: Properly typed formatting functionsThe
posExp
andformat
functions now have proper TypeScript type annotations, improving type safety throughout the library.
156-202
: Enhanced type safety in Decimal constructorThe Decimal constructor now has proper TypeScript type annotations, improving type safety when creating new Decimal instances and calling methods on them.
204-208
: Properly typed static methodsThe static methods of the Decimal constructor are now properly typed, ensuring type safety when using these utility methods.
230-241
: Type-safe toFixed functionAdding TypeScript type annotations to the
toFixed
function improves type safety and clarifies the function's purpose.
243-272
: Well-typed formatInteger function with options interfaceThe
formatInteger
function now has a proper TypeScript interface for its options, improving type safety and making the function's parameters clearer.
274-287
: Type-safe reverseString functionAdding TypeScript type annotations to the
reverseString
function improves type safety.
289-307
: Well-typed formatDecimal function with options interfaceThe
formatDecimal
function now has a proper TypeScript interface for its options, improving type safety and making the function's parameters clearer.
309-352
: Comprehensive type definitions for formatNumberThe addition of a detailed TypeScript interface for formatNumber options and proper type annotations for the function significantly improves type safety and documentation.
354-373
: Type-safe recoverNumber functionAdding TypeScript type annotations to the
recoverNumber
function improves type safety and clarifies the function's purpose.packages/utils/src/array/index.ts (10)
26-41
: Enhanced type safety with generics in indexOfImplementing generic type parameter
<T>
in theindexOf
function improves type safety by ensuring consistent types throughout the function call and return.
49-56
: Simplified type handling in find functionThe
find
function now uses generics for better type safety, though there's a complex type cast that could potentially be simplified in the future.
66-80
: Type-safe remove function with genericsThe
remove
function now uses generics to ensure type consistency between the input array and return value.
88-111
: Enhanced sort function with proper constraint on generic typeThe
sort
function now uses generics with a constraint (T extends Record<string, any>
) to ensure that the array elements have the properties required for sorting.
121-131
: Type-safe push function with genericsThe
push
function now uses generics to ensure type consistency between the input array and return value.
139-157
: Well-typed unique function with genericsThe
unique
function now uses generics to ensure type consistency between the input array and return value.
159-170
: Properly typed extend functionThe
extend
function now has explicit typing asRecord<string, any>
for its parameters and return value.
178-191
: Type-safe toObject functionThe
toObject
function now properly types its input array and return value asRecord<string, any>
.
199-235
: Enhanced type safety in transformPidToChildren functionThe
transformPidToChildren
function now has explicit typing for its parameters and return value, improving type safety when working with tree data structures.
239-262
: Well-typed tree data transformation functionThe
transformTreeData
function now properly handles both single objects and arrays with appropriate type annotations, and uses a cleaner spread operator for object cloning.packages/utils/src/dataset/index.ts (4)
17-120
: Well-structured TypeScript interfaces with comprehensive JSDoc comments.The addition of these interfaces greatly enhances type safety and code documentation. Each interface has a clear purpose with descriptive comments, and properties are appropriately typed with optional markers where needed.
122-152
: Improved type safety for getFilterStr function.The function now has clear parameter and return types, making its usage more predictable.
154-174
: Good addition of null check for getNsObj function.The improved type annotations enhance clarity, and the new undefined check on line 165 makes the function more robust.
267-270
: Improved type safety with explicit response type.The addition of type annotations for the response object enhances type safety and code clarity.
packages/utils/src/bigInt/index.ts (6)
15-21
: Great addition of JSDoc documentation for supportBigInt function.The function now clearly indicates its purpose and return type, improving code readability and maintainability.
23-71
: Comprehensive type annotations for trimNumber function.The detailed return type definition enhances type safety and makes the function's output structure explicit. The JSDoc comment also clearly explains the function's purpose.
73-81
: Improved documentation and type annotation for isE function.The function now has clear parameter and return types with a descriptive comment about its purpose.
83-103
: Enhanced null/undefined handling in isNativeStringType.The addition of a type check at line 99 improves the function's robustness.
119-127
: Optional chaining opportunity in getNumberPrecision function.The use of optional chaining is a good improvement for handling potentially undefined values.
571-613
: Well-documented toFixed function with clear type annotations.The function now has a comprehensive JSDoc comment and explicit type annotations, greatly improving code clarity.
packages/utils/src/validate/util.ts (6)
16-22
: Clear documentation for the warning function.The JSDoc comment clearly states that the function is not implemented yet, which is valuable information for developers.
24-45
: Improved type safety for convertFieldsError function.The explicit type annotations for parameters and return value enhance the function's clarity and usability.
93-122
: Enhanced null handling in isNativeStringType function.The added check for undefined input improves the function's robustness.
145-152
: Good addition of JSDoc documentation for isEmptyObject.Clear documentation helps developers understand the function's purpose and use cases.
232-297
: Comprehensive type definitions for asyncMap function.The detailed type annotations greatly improve the function's clarity and maintainability.
321-346
: Well-documented deepMerge function with proper type annotations.The function now has clear parameter and return types, making its usage more predictable.
🧰 Tools
🪛 Biome (1.9.4)
[error] 331-332: Don't use 'Function' as a type.
Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.
(lint/complexity/noBannedTypes)
export function afterLeave( | ||
instance: { $once: (event: string, callback: Function) => void; $on: (event: string, callback: Function) => void }, | ||
callback: Function, | ||
speed: number = Speed, | ||
once = false | ||
): void { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Type definitions improve function signature clarity, but consider refining the Function type.
The TypeScript type annotations significantly improve the function signature by clearly defining parameter types and return type. However, using the Function
type is discouraged as it's too generic.
Consider using more specific function types:
- callback: Function,
+ callback: (...args: any[]) => void,
🏁 Script executed:
#!/bin/bash
# Check if the Function type is used elsewhere in the codebase
rg "callback: Function" --type ts
Length of output: 936
Refine callback type signature for improved type-safety
The current use of the generic Function
type in the afterLeave
function (and similar patterns across the codebase) can be made more explicit. Instead of using:
- callback: Function,
+ callback: (...args: any[]) => void,
this change will enhance clarity and ensure better type checking. Please update the type accordingly in packages/utils/src/after-leave/index.ts
(lines 35-40) and consider aligning similar patterns in other parts of the codebase if appropriate.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export function afterLeave( | |
instance: { $once: (event: string, callback: Function) => void; $on: (event: string, callback: Function) => void }, | |
callback: Function, | |
speed: number = Speed, | |
once = false | |
): void { | |
export function afterLeave( | |
instance: { $once: (event: string, callback: Function) => void; $on: (event: string, callback: Function) => void }, | |
callback: (...args: any[]) => void, | |
speed: number = Speed, | |
once = false | |
): void { |
/** 是否为空 */ | ||
empty?: boolean | ||
/** 原始值 */ | ||
origin!: string | ||
/** 是否为负数 */ | ||
negative?: boolean | ||
/** 整数部分 */ | ||
integer?: bigint | string | ||
/** 小数部分 */ | ||
decimal?: bigint | ||
/** 小数长度 */ | ||
decimalLen?: number | ||
/** 是否为NaN */ | ||
nan?: boolean | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Consider using non-null assertion more safely in BigIntDecimal class.
The non-null assertions in the class methods assume properties will always be defined, which could lead to runtime errors.
🏁 Script executed:
#!/bin/bash
# Identify occurrences where the class is instantiated without properly initializing the required properties
rg -A 5 "new BigIntDecimal"
Length of output: 4101
Action Required: Enhance Safety Around Non-Null Assertions in BigIntDecimal
Although the test cases currently instantiate BigIntDecimal with valid input values (e.g., '123.45'
, ''
, and '-'
), the class still relies on non-null assertions (e.g., for the origin
property). This approach assumes that properties will always be initialized correctly, which might not hold in all edge cases—potentially leading to runtime errors.
Recommendations:
- Ensure Constructor Guarantees: Verify that the constructor (or factory methods) enforces the proper initialization of all non-null properties (such as
origin
) so that the non-null assertions become redundant. - Runtime Guards: Consider adding runtime validations or default initializations in methods that access these properties, thereby safeguarding against any unforeseen scenarios where properties might be absent.
- Review Impact: Revisit any methods that use these properties to confirm that additional null or undefined checks are not needed.
给utils包中的函数添加注释、ts 类型声明和 vitest 测试用例
PR
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Issue Number: N/A
What is the new behavior?
Does this PR introduce a breaking change?
Other information
Summary by CodeRabbit