1
Fork 0

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

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-26 16:36:05 +02:00 committed by prescientmoon
parent cd5dc00dbd
commit ab5e468375
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
3 changed files with 82 additions and 0 deletions

View file

@ -22,6 +22,7 @@ export * from './or'
export * from './orLazy'
export * from './toArray'
export * from './toNullable'
export * from './unpack'
export * from './unwrap'
export * from './withDefault'
export * from './withDefaultLazy'

View file

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

View file

@ -0,0 +1,20 @@
import { Lazy, Mapper } from '../internalTypes'
import { Option } from '../types'
import { withDefaultLazy } from './withDefaultLazy'
import { map } from './map'
/**
* Like unwrap, but the default value is lazy,
* and will only be computed if the Option is None.
*
* @param _default The lazy value to use in case option is None.
* @param mapper The function to pass the inner value to.
* @param option The option to unpack.
*/
export const unpack = <T, U>(
_default: Lazy<U>,
mapper: Mapper<T, U>,
option: Option<T>
) => {
return withDefaultLazy(_default, map(mapper, option))
}