typescript(option): feat: added the 'orLazy' helper
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
a525a46bca
commit
6a8191cc34
5 changed files with 162 additions and 0 deletions
typescript/option/src/helpers
|
@ -18,6 +18,7 @@ export * from './map'
|
|||
export * from './mapAsync'
|
||||
export * from './optionify'
|
||||
export * from './or'
|
||||
export * from './orLazy'
|
||||
export * from './toArray'
|
||||
export * from './toNullable'
|
||||
export * from './withDefault'
|
||||
|
|
48
typescript/option/src/helpers/orLazy.test.ts
Normal file
48
typescript/option/src/helpers/orLazy.test.ts
Normal file
|
@ -0,0 +1,48 @@
|
|||
import { expect } from 'chai'
|
||||
import { constantly } from '@thi.ng/compose'
|
||||
import { orLazy } from './orLazy'
|
||||
import { someX } from '../../test/constants'
|
||||
import { None } from '../types'
|
||||
import { spy } from 'sinon'
|
||||
|
||||
describe('The orLazy helper', () => {
|
||||
it("should return the first argument if it's Some", () => {
|
||||
// act
|
||||
const result = orLazy(someX, constantly(None))
|
||||
|
||||
// asser
|
||||
expect(result).to.equal(someX)
|
||||
})
|
||||
|
||||
it('should return the return of the second argument if the first is None', () => {
|
||||
// act
|
||||
const orSome = orLazy(None, constantly(someX))
|
||||
const orNone = orLazy(None, constantly(None))
|
||||
|
||||
// assert
|
||||
expect(orSome).to.equal(someX)
|
||||
expect(orNone).to.equal(None)
|
||||
})
|
||||
|
||||
it('should not evaluate the second argument if the first one is Some', () => {
|
||||
// arrange
|
||||
const func = spy(constantly(someX))
|
||||
|
||||
// act
|
||||
orLazy(someX, func)
|
||||
|
||||
// assert
|
||||
expect(func.called).to.be.false
|
||||
})
|
||||
|
||||
it('should evaluate the second argument if the first one is None', () => {
|
||||
// arrange
|
||||
const func = spy(constantly(someX))
|
||||
|
||||
// act
|
||||
orLazy(None, func)
|
||||
|
||||
// assert
|
||||
expect(func.called).to.be.true
|
||||
})
|
||||
})
|
17
typescript/option/src/helpers/orLazy.ts
Normal file
17
typescript/option/src/helpers/orLazy.ts
Normal file
|
@ -0,0 +1,17 @@
|
|||
import { isSome } from './isSome'
|
||||
import { Option } from '../types'
|
||||
|
||||
/**
|
||||
* Lazy version of or.
|
||||
* The second argument will only be evaluated if the first argument is Nothing.
|
||||
*
|
||||
* @param a The first argument.
|
||||
* @param b The second argument.
|
||||
*/
|
||||
export const orLazy = <T>(a: Option<T>, b: () => Option<T>) => {
|
||||
if (isSome(a)) {
|
||||
return a
|
||||
}
|
||||
|
||||
return b()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue