From 457f1ee53ebd011bce3e41e34dd2be885a1ac3ec Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Thu, 26 Dec 2019 17:05:16 +0200 Subject: [PATCH] typescript(option): feat: added the 'combine' helper Signed-off-by: prescientmoon --- typescript/option/src/helpers/combine.test.ts | 26 +++++++++++++++++++ typescript/option/src/helpers/combine.ts | 19 ++++++++++++++ typescript/option/src/helpers/external.ts | 3 ++- 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 typescript/option/src/helpers/combine.test.ts create mode 100644 typescript/option/src/helpers/combine.ts diff --git a/typescript/option/src/helpers/combine.test.ts b/typescript/option/src/helpers/combine.test.ts new file mode 100644 index 0000000..cd96495 --- /dev/null +++ b/typescript/option/src/helpers/combine.test.ts @@ -0,0 +1,26 @@ +import { expect } from 'chai' +import { combine } from './combine' +import { someX } from '../../test/constants' +import { None } from '../types' +import { isSome } from './isSome' + +describe('The combine helepr', () => { + it('should return None if the iterable contains any Nones', () => { + // act + const result = combine([someX, someX, None, someX, someX]) + + // assert + expect(result).to.equal(None) + }) + + it("should return Some when the iterable doesn't contain any None", () => { + // arrange + const items = Array(50).fill(someX) + + // act + const result = combine(items) + + // act + expect(isSome(result)).to.be.true + }) +}) diff --git a/typescript/option/src/helpers/combine.ts b/typescript/option/src/helpers/combine.ts new file mode 100644 index 0000000..b922a57 --- /dev/null +++ b/typescript/option/src/helpers/combine.ts @@ -0,0 +1,19 @@ +import { Option, None, Some } from '../types' +import { isNone } from './isNone' + +/** + * If every Option in the list is present, return all of the values unwrapped. + * If there are any Nones, the whole function fails and returns None. + * + * @param iterable The iterable to combine. + */ +export const combine = (iterable: Iterable>) => { + const set = new Set(iterable) + + if (set.has(None)) { + return None + } + + const array = Array.from(set) as T[] + return array as Option +} diff --git a/typescript/option/src/helpers/external.ts b/typescript/option/src/helpers/external.ts index 9cddd76..a992f59 100644 --- a/typescript/option/src/helpers/external.ts +++ b/typescript/option/src/helpers/external.ts @@ -1,5 +1,6 @@ export * from './bind' export * from './bindAsync' +export * from './combine' export * from './count' export * from './exists' export * from './filter' @@ -24,6 +25,6 @@ export * from './toArray' export * from './toNullable' export * from './unpack' export * from './unwrap' +export * from './values' export * from './withDefault' export * from './withDefaultLazy' -export * from './values'