ES6 has support for custom iterators.
It'd be great if we could implement Symbol.iterator, so we could write code like so:
const foo: Option<string> = getFooSomeHow();
const bar: Option<string> = getBarSomeHow();
const fooBar = [...foo, ...bar];
@bioball What would happen in the case of foo or bar being None in the above example? Would the spread operator simply do nothing?
In that case, the spread operator expands it to nothing, and fooBar would end up being an empty array.
Hmmm, I think it's an interesting proposal, but it's also sort of outside of the norm of how most languages use the Maybe/Option type...
You could also write something like this and use it as a wrapper for such cases:
export const toSpreadable = <A>(opt: Option<A>): A[] => opt.fold([] as A[], x => [x])
Like:
const fooBar = [...toSpreadable(foo), ...toSpreadable(bar)]
Note: toSpreadable is a natural transformation and can be derived from the Foldable instance
import { toArray } from 'fp-ts/lib/Foldable2v'
import { option } from 'fp-ts/lib/Option'
const toSpreadable = toArray(option)
Most helpful comment
Note:
toSpreadableis a natural transformation and can be derived from theFoldableinstance