Skip to content

Commit

Permalink
feat: 新增 tryGet
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jun 19, 2019
1 parent 6b1c025 commit 115a49d
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export * from './startsWith'
export * from './sum'
export * from './throttle'
export * from './times'
export * from './tryGet'
export * from './unique'
export * from './URI'
export * from './values'
Expand Down
39 changes: 39 additions & 0 deletions src/tryGet.test.ts
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,
)
})
42 changes: 42 additions & 0 deletions src/tryGet.ts
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
}

0 comments on commit 115a49d

Please sign in to comment.