-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { jestExpectEqual } from './enhanceJest' | ||
import { tryGet } from './tryGet' | ||
|
||
const obj = { | ||
x: 1, | ||
s: '字符串', | ||
y: { | ||
yy: { | ||
yyyy: { | ||
yyyyy: () => 'hello', | ||
yyyyy2: true, | ||
}, | ||
yyyy2: [0, 1, 2, 3], | ||
yyyy3: /.+/, | ||
}, | ||
}, | ||
z: { | ||
zz: null, | ||
zzz: undefined, | ||
zzzz: 'hoho', | ||
}, | ||
} | ||
|
||
test('表现正常', () => { | ||
jestExpectEqual( | ||
tryGet(() => obj.y.yy), | ||
obj.y.yy, | ||
) | ||
|
||
jestExpectEqual( | ||
tryGet(() => (obj as any).y.yy.xxx.ffs), | ||
undefined, | ||
) | ||
|
||
jestExpectEqual( | ||
tryGet(() => (obj as any).y.yy.xxx.ffs, 1), | ||
1, | ||
) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
export interface TryGetAccessor<R> { | ||
(): R, | ||
} | ||
|
||
/** | ||
* 尝试执行 `accessor` 返回值,若其报错,返回默认值 `defaultValue`。 | ||
* | ||
* @param accessor 值获取器 | ||
* @param defaultValue 默认值 | ||
* @returns 返回结果值 | ||
* @example | ||
* ```ts | ||
* const obj = { x: 1 } | ||
* tryGet(() => obj.x, 2) // => 1 | ||
* tryGet(() => obj.x.y, 2) // => 2 | ||
* ``` | ||
*/ | ||
export function tryGet<R>(accessor: TryGetAccessor<R>, defaultValue: R): R | ||
|
||
/** | ||
* 尝试执行 `accessor` 返回值,若其报错,返回 `undefined`。 | ||
* | ||
* @param accessor 值获取器 | ||
* @returns 返回结果值 | ||
* @example | ||
* ```ts | ||
* const obj = { x: 1 } | ||
* tryGet(() => obj.x) // => 1 | ||
* tryGet(() => obj.x.y) // => undefined | ||
* ``` | ||
*/ | ||
export function tryGet<R>(accessor: TryGetAccessor<R>): R | undefined | ||
|
||
export function tryGet<R>(accessor: TryGetAccessor<R>, defaultValue?: R): R | undefined { | ||
let result: R | undefined | ||
try { | ||
result = accessor() | ||
} catch (e) { | ||
result = defaultValue | ||
} | ||
return result | ||
} |