Skip to content

Commit 93c5b7c

Browse files
feat(maybe): add valueOrNull() (#161)
1 parent 40cd082 commit 93c5b7c

File tree

5 files changed

+263
-2
lines changed

5 files changed

+263
-2
lines changed

package-lock.json

Lines changed: 233 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/maybe/maybe.interface.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ export interface IMaybe<T> extends IMonad<T> {
3232
*/
3333
valueOrUndefined(): T | undefined
3434

35+
/**
36+
* Unwrap a Maybe with its value or return null if its empty
37+
*/
38+
valueOrNull(): T | null
39+
3540
/**
3641
* Unwrap a Maybe with its value or return and empty list
3742
*/

src/maybe/maybe.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,22 @@ describe('Maybe', () => {
394394
})
395395
})
396396

397+
describe('when returning a value or null', () => {
398+
it('should handle "none" case', () => {
399+
const sut = undefined as string | undefined
400+
const maybeAString = maybe(sut).valueOrNull()
401+
402+
expect(maybeAString).toBeNull()
403+
})
404+
405+
it('should handle "some" case', () => {
406+
const sut = 'actual input' as string | undefined
407+
const maybeAString = maybe(sut).valueOrNull()
408+
409+
expect(maybeAString).toEqual('actual input')
410+
})
411+
})
412+
397413
describe('when returning an array', () => {
398414
it('should handle "none" case', () => {
399415
const sut = undefined as string | undefined

src/maybe/maybe.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ export class Maybe<T> implements IMaybe<T> {
3232
return this.isSome() ? this.value as NonNullable<T> : undefined
3333
}
3434

35+
public valueOrNull(): T | null {
36+
return this.isSome() ? this.value as NonNullable<T> : null
37+
}
38+
3539
public valueOrCompute(fn: () => NonNullable<T>): NonNullable<T> {
3640
return this.isSome() ? this.value as NonNullable<T> : fn()
3741
}

tsconfig.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
"es2015",
88
"dom"
99
],
10+
"types": [
11+
"node",
12+
"jest"
13+
],
1014
"isolatedModules": false,
1115
"experimentalDecorators": true,
1216
"emitDecoratorMetadata": true,
@@ -27,6 +31,6 @@
2731
"downlevelIteration": true
2832
},
2933
"include": [
30-
"src/**/*.ts"
34+
"src"
3135
]
3236
}

0 commit comments

Comments
 (0)