1
Fork 0

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

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-26 16:16:09 +02:00 committed by prescientmoon
parent 6f36c3d826
commit 6dc868c5fb
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
4 changed files with 68 additions and 0 deletions

View file

@ -0,0 +1,50 @@
import { expect } from 'chai'
import { withDefaultLazy } from './withDefaultLazy'
import { None, Some } from '../types'
import { alwaysX, x, someX } from '../../test/constants'
import { constantly } from '@thi.ng/compose'
import { spy } from 'sinon'
describe('The withDefaultLazy helper', () => {
describe('When given None', () => {
it('should return the default when given None', () => {
// act
const result = withDefaultLazy(alwaysX, None)
// assert
expect(result).to.equal(x)
})
it('should call the lazy default', () => {
// arrange
const func = spy(constantly(x))
// act
withDefaultLazy(func, None)
// assert
expect(func.called).to.be.true
})
})
describe('When given Some', () => {
it('should return the inner value', () => {
// act
const result = withDefaultLazy(constantly(0), Some(1))
// assert
expect(result).to.equal(1)
})
it('should not call the lazy default', () => {
// arrange
const func = spy(constantly(x))
// act
withDefaultLazy(func, someX)
// assert
expect(func.called).to.be.false
})
})
})

View file

@ -0,0 +1,16 @@
import { Option } from '../types'
import { isSome } from './isSome'
import { Lazy } from '../internalTypes'
import { get } from './get'
/**
* Same as withDefault but the default is only evaluated when the option is None.
*
* @param _default Function returning the default value to use.
* @param option The option to get the default of.
*/
export const withDefaultLazy = <T>(_default: Lazy<T>, option: Option<T>) => {
if (isSome(option)) {
return get(option)
} else return _default()
}

View file

@ -6,3 +6,4 @@ export type Predicate<T> = (v: T) => boolean
export type Folder<T, U> = (s: U, v: T) => U
export type BackFolder<T, U> = (v: T, s: U) => U
export type Nullable<T> = T | null
export type Lazy<T> = () => T

View file

@ -7,4 +7,5 @@ export const x = Symbol('x')
// same as x but for some
export const someX = Some(x)
export const alwaysX = constantly(x)
export const alwaysSomeX = constantly(someX)