Hi there, thanks for the fantastic library.
I have an array of options and I want to flatten it to an array of the Some values, filtering out the Nones.
How would you recommend doing this?
Is this something you think could be added to the library?
Thanks,
Oliver
import { Option, some, none } from 'fp-ts/lib/Option'
import * as array from 'fp-ts/lib/Array'
import { identity } from 'fp-ts/lib/unction'
export function mapOption<A, B>(f: (a: A) => Option<B>, as: Array<A>): Array<B> {
return array.chain(a => f(a).fold(() => array.empty(), array.of), as)
}
export function catOptions<A>(as: Array<Option<A>>): Array<A> {
return mapOption<Option<A>, A>(identity, as)
}
const as = [none, some(1), none, some(2)]
console.log(catOptions(as)) // => [1, 2]
Is this something you think could be added to the library?
Good idea
Opss.. actually they are already implemented :) (Array module) https://github.com/gcanti/fp-ts/blob/master/src/Array.ts#L213
Thanks!
What's the status of this issue? Is there a function like array.rights that works with Option instead of Either?
Hi, you can use compact:
import { compact } from 'fp-ts/lib/Array';
declare const as: Array<Option<number>>
const bs: Array<number> = compact(as)
Thanks!
Most helpful comment
Hi, you can use
compact: