typescript(option): feat: added an optionify helper
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
aade2d23d7
commit
cd4aba143c
|
@ -15,6 +15,7 @@ export * from './isSome'
|
|||
export * from './iter'
|
||||
export * from './map'
|
||||
export * from './mapAsync'
|
||||
export * from './optionify'
|
||||
export * from './toArray'
|
||||
export * from './toNullable'
|
||||
export * from './withDefault'
|
||||
|
|
17
typescript/option/src/helpers/optionify.test.ts
Normal file
17
typescript/option/src/helpers/optionify.test.ts
Normal file
|
@ -0,0 +1,17 @@
|
|||
import { expect } from 'chai'
|
||||
import { optionify } from './optionify'
|
||||
import { fromNullable } from './fromNullable'
|
||||
|
||||
describe('The optionify helper', () => {
|
||||
it('should create a function which returns an option instead of a nullable', () => {
|
||||
// arrange
|
||||
const func = (a: number, b: number) => (a > b ? a + b : null)
|
||||
|
||||
// act
|
||||
const result = optionify(func)
|
||||
|
||||
// assert
|
||||
expect(result(1, 2)).to.equal(fromNullable(func(1, 2)))
|
||||
expect(result(2, 1)).to.equal(fromNullable(func(2, 1)))
|
||||
})
|
||||
})
|
15
typescript/option/src/helpers/optionify.ts
Normal file
15
typescript/option/src/helpers/optionify.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import { fromNullable } from './fromNullable'
|
||||
|
||||
/**
|
||||
* Takes a function which returns a nullable and creates
|
||||
* a function which returns an Option.
|
||||
* In functional programming this would be the same as
|
||||
* composing the function with fromNullable.
|
||||
*
|
||||
* @param f The function to optionify
|
||||
*/
|
||||
export const optionify = <T extends unknown[], U>(
|
||||
f: (...args: T) => U | null
|
||||
) => {
|
||||
return (...args: T) => fromNullable(f(...args))
|
||||
}
|
Loading…
Reference in a new issue