1
Fork 0

typescript(option): feat: added an or helper

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

View file

@ -16,6 +16,7 @@ export * from './iter'
export * from './map'
export * from './mapAsync'
export * from './optionify'
export * from './or'
export * from './toArray'
export * from './toNullable'
export * from './withDefault'

View file

@ -0,0 +1,26 @@
import { expect } from 'chai'
import { or } from './or'
import { someX } from '../../test/constants'
import { None } from '../types'
describe('The or helper', () => {
describe('When the first argument is None', () => {
it('should return the second argument', () => {
// act
const orSome = or(None, someX)
const orNone = or(None, None)
// assert
expect(orSome).to.equal(someX)
expect(orNone).to.equal(None)
})
})
it("should return the first argument when it's not None", () => {
// act
const result = or(someX, None)
// assert
expect(result).to.equal(someX)
})
})

View file

@ -0,0 +1,20 @@
import { Option } from '../types'
import { isSome } from './isSome'
/**
* Returns the first value that is present, like the boolean ||.
* Both values will be computed.
* There is no short-circuiting.
* If your second argument is expensive to calculate and
* you need short circuiting, use orLazy instead.
*
* @param a The first argument.
* @param b The second argument.
*/
export const or = <T>(a: Option<T>, b: Option<T>): Option<T> => {
if (isSome(a)) {
return a
} else {
return b
}
}