1
Fork 0

typescript(option): feat: added an optionify helper

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-25 15:17:22 +02:00 committed by prescientmoon
parent aade2d23d7
commit cd4aba143c
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
3 changed files with 33 additions and 0 deletions

View file

@ -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'

View 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)))
})
})

View 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))
}