From 668c33b9fb60ecb5890c44bb72a90200b3a5e227 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Thu, 26 Dec 2019 15:52:15 +0200 Subject: [PATCH] typescript(option): feat: added the 'unwrap' helper Signed-off-by: prescientmoon --- typescript/option/src/helpers/external.ts | 1 + typescript/option/src/helpers/unwrap.test.ts | 37 ++++++++++++++++++++ typescript/option/src/helpers/unwrap.ts | 20 +++++++++++ 3 files changed, 58 insertions(+) create mode 100644 typescript/option/src/helpers/unwrap.test.ts create mode 100644 typescript/option/src/helpers/unwrap.ts diff --git a/typescript/option/src/helpers/external.ts b/typescript/option/src/helpers/external.ts index 889f6de..ee8e2cb 100644 --- a/typescript/option/src/helpers/external.ts +++ b/typescript/option/src/helpers/external.ts @@ -22,4 +22,5 @@ export * from './or' export * from './orLazy' export * from './toArray' export * from './toNullable' +export * from './unwrap' export * from './withDefault' diff --git a/typescript/option/src/helpers/unwrap.test.ts b/typescript/option/src/helpers/unwrap.test.ts new file mode 100644 index 0000000..5f2ee43 --- /dev/null +++ b/typescript/option/src/helpers/unwrap.test.ts @@ -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 + }) + }) +}) diff --git a/typescript/option/src/helpers/unwrap.ts b/typescript/option/src/helpers/unwrap.ts new file mode 100644 index 0000000..4757468 --- /dev/null +++ b/typescript/option/src/helpers/unwrap.ts @@ -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 = ( + _default: U, + mapper: Mapper, + option: Option +) => { + return withDefault(_default, map(mapper, option)) +}