1
Fork 0

typescript(option): feat: added a first helper

Signed-off-by: prescientmoon <git@moonythm.dev>
This commit is contained in:
Matei Adriel 2019-12-25 15:40:47 +02:00 committed by prescientmoon
parent 9989591593
commit a525a46bca
Signed by: prescientmoon
SSH key fingerprint: SHA256:UUF9JT2s8Xfyv76b8ZuVL7XrmimH4o49p4b+iexbVH4
3 changed files with 50 additions and 0 deletions

View file

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

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

View 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
}