typescript(option): feat: added an or helper
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
cd4aba143c
commit
9989591593
|
@ -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'
|
||||
|
|
26
typescript/option/src/helpers/or.test.ts
Normal file
26
typescript/option/src/helpers/or.test.ts
Normal 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)
|
||||
})
|
||||
})
|
20
typescript/option/src/helpers/or.ts
Normal file
20
typescript/option/src/helpers/or.ts
Normal 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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue