diff --git a/typescript/option/src/helpers/external.ts b/typescript/option/src/helpers/external.ts index 7152985..36a2cc5 100644 --- a/typescript/option/src/helpers/external.ts +++ b/typescript/option/src/helpers/external.ts @@ -16,6 +16,7 @@ export * from './iter' export * from './map' export * from './mapAsync' export * from './optionify' +export * from './or' export * from './toArray' export * from './toNullable' export * from './withDefault' diff --git a/typescript/option/src/helpers/or.test.ts b/typescript/option/src/helpers/or.test.ts new file mode 100644 index 0000000..a7205d0 --- /dev/null +++ b/typescript/option/src/helpers/or.test.ts @@ -0,0 +1,26 @@ +import { expect } from 'chai' +import { or } from './or' +import { someX } from '../../test/constants' +import { None } from '../types' + +describe('The or helper', () => { + describe('When the first argument is None', () => { + it('should return the second argument', () => { + // act + const orSome = or(None, someX) + const orNone = or(None, None) + + // assert + expect(orSome).to.equal(someX) + expect(orNone).to.equal(None) + }) + }) + + it("should return the first argument when it's not None", () => { + // act + const result = or(someX, None) + + // assert + expect(result).to.equal(someX) + }) +}) diff --git a/typescript/option/src/helpers/or.ts b/typescript/option/src/helpers/or.ts new file mode 100644 index 0000000..b717565 --- /dev/null +++ b/typescript/option/src/helpers/or.ts @@ -0,0 +1,20 @@ +import { Option } from '../types' +import { isSome } from './isSome' + +/** + * Returns the first value that is present, like the boolean ||. + * Both values will be computed. + * There is no short-circuiting. + * If your second argument is expensive to calculate and + * you need short circuiting, use orLazy instead. + * + * @param a The first argument. + * @param b The second argument. + */ +export const or = (a: Option, b: Option): Option => { + if (isSome(a)) { + return a + } else { + return b + } +}