typescript(option): feat: added the 'unwrap' helper
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
5ea670e3b9
commit
668c33b9fb
|
@ -22,4 +22,5 @@ export * from './or'
|
|||
export * from './orLazy'
|
||||
export * from './toArray'
|
||||
export * from './toNullable'
|
||||
export * from './unwrap'
|
||||
export * from './withDefault'
|
||||
|
|
37
typescript/option/src/helpers/unwrap.test.ts
Normal file
37
typescript/option/src/helpers/unwrap.test.ts
Normal 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
|
||||
})
|
||||
})
|
||||
})
|
20
typescript/option/src/helpers/unwrap.ts
Normal file
20
typescript/option/src/helpers/unwrap.ts
Normal 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))
|
||||
}
|
Loading…
Reference in a new issue