typescript(option): feat: added a first helper
Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
parent
9989591593
commit
a525a46bca
|
@ -3,6 +3,7 @@ export * from './bindAsync'
|
||||||
export * from './count'
|
export * from './count'
|
||||||
export * from './exists'
|
export * from './exists'
|
||||||
export * from './filter'
|
export * from './filter'
|
||||||
|
export * from './first'
|
||||||
export * from './flat'
|
export * from './flat'
|
||||||
export * from './fold'
|
export * from './fold'
|
||||||
export * from './foldback'
|
export * from './foldback'
|
||||||
|
|
32
typescript/option/src/helpers/first.test.ts
Normal file
32
typescript/option/src/helpers/first.test.ts
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
import { constantly } from '@thi.ng/compose'
|
||||||
|
import { expect } from 'chai'
|
||||||
|
import { someX } from '../../test/constants'
|
||||||
|
import { None, Option } from '../types'
|
||||||
|
import { first } from './first'
|
||||||
|
|
||||||
|
describe('The first helper', () => {
|
||||||
|
it('should return the first Some if there is any', () => {
|
||||||
|
// act
|
||||||
|
const head = first([someX, None])
|
||||||
|
const middle = first([None, someX, None])
|
||||||
|
const tail = first([None, someX])
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(head).to.equal(someX)
|
||||||
|
expect(middle).to.equal(someX)
|
||||||
|
expect(tail).to.equal(someX)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("should return None if there isn't any Some", () => {
|
||||||
|
// arrange
|
||||||
|
const array: Option<unknown>[] = Array(50)
|
||||||
|
.fill(1)
|
||||||
|
.map(constantly(None))
|
||||||
|
|
||||||
|
// act
|
||||||
|
const result = first(array)
|
||||||
|
|
||||||
|
// assert
|
||||||
|
expect(result).to.equal(None)
|
||||||
|
})
|
||||||
|
})
|
17
typescript/option/src/helpers/first.ts
Normal file
17
typescript/option/src/helpers/first.ts
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
import { isSome } from './isSome'
|
||||||
|
import { Option, None } from '../types'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the first Some in an iterable. If there isn't any returns None.
|
||||||
|
*
|
||||||
|
* @param elemenets The elements to find the first Some in.
|
||||||
|
*/
|
||||||
|
export const first = <T>(elemenets: Iterable<Option<T>>) => {
|
||||||
|
for (const option of elemenets) {
|
||||||
|
if (isSome(option)) {
|
||||||
|
return option
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return None
|
||||||
|
}
|
Loading…
Reference in a new issue