1
Fork 0

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

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-26 17:05:16 +02:00 committed by prescientmoon
parent 08b28804e0
commit 457f1ee53e
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
3 changed files with 47 additions and 1 deletions

View file

@ -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
})
})

View file

@ -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 = <T>(iterable: Iterable<Option<T>>) => {
const set = new Set(iterable)
if (set.has(None)) {
return None
}
const array = Array.from(set) as T[]
return array as Option<T[]>
}

View file

@ -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'