1
Fork 0

typescript(option): feat: added the 'orLazy' helper

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-25 15:51:56 +02:00 committed by prescientmoon
parent a525a46bca
commit 6a8191cc34
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
5 changed files with 162 additions and 0 deletions
typescript/option/src/helpers

View file

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

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

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