Skip to content

Commit

Permalink
feat: 新增 defaultTo
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jun 17, 2019
1 parent a80b6e1 commit a587b71
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/defaultTo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { defaultTo } from './defaultTo'
import { jestExpectEqual } from './enhanceJest'

test('表现正常', () => {
jestExpectEqual(
defaultTo(1, 2),
1,
)

;[NaN, null, undefined].forEach(item => {
jestExpectEqual(
defaultTo(item, 2),
2,
)
})
})
19 changes: 19 additions & 0 deletions src/defaultTo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { isNaN, isNil } from './is'

/**
* 检查 `value` 是否是 `null`、`undefined`、`NaN`,是则返回 `defaultValue`,否则返回 `value`。
*
* @param value 要检查的值
* @param defaultValue 默认值
* @returns 返回结果值
* @example
* ```ts
* defaultTo(1, 2) // => 1
* defaultTo(NaN, 2) // => 2
* defaultTo(null, 2) // => 2
* defaultTo(undefined, 2) // => 2
* ```
*/
export function defaultTo<T>(value: T, defaultValue: T): T {
return isNil(value) || isNaN(value) ? defaultValue : value
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './castArray'
export * from './chunk'
export * from './clamp'
export * from './debounce'
export * from './defaultTo'
export * from './Disposer'
export * from './EasyStorage'
export * from './EasyValidator'
Expand Down

0 comments on commit a587b71

Please sign in to comment.