1
Fork 0

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

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-26 15:52:15 +02:00 committed by prescientmoon
parent 5ea670e3b9
commit 668c33b9fb
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
3 changed files with 58 additions and 0 deletions

View file

@ -22,4 +22,5 @@ export * from './or'
export * from './orLazy' export * from './orLazy'
export * from './toArray' export * from './toArray'
export * from './toNullable' export * from './toNullable'
export * from './unwrap'
export * from './withDefault' export * from './withDefault'

View file

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

View file

@ -0,0 +1,20 @@
import { Mapper } from '../internalTypes'
import { Option } from '../types'
import { withDefault } from './withDefault'
import { map } from './map'
/**
* Apply the function to the value in the Maybe and return it unwrapped.
* If the Maybe is Nothing, use the default value instead.
*
* @param _default The default value to use.
* @param mapper Function to apply to the inner value.
* @param option Option to unwrap.
*/
export const unwrap = <T, U>(
_default: U,
mapper: Mapper<T, U>,
option: Option<T>
) => {
return withDefault(_default, map(mapper, option))
}