typescript(option): feat: added the 'combine' helper
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
08b28804e0
commit
457f1ee53e
26
typescript/option/src/helpers/combine.test.ts
Normal file
26
typescript/option/src/helpers/combine.test.ts
Normal 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
|
||||
})
|
||||
})
|
19
typescript/option/src/helpers/combine.ts
Normal file
19
typescript/option/src/helpers/combine.ts
Normal 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[]>
|
||||
}
|
|
@ -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'
|
||||
|
|
Loading…
Reference in a new issue