Skip to content

Instantly share code, notes, and snippets.

@kylpo
Last active August 4, 2020 01:29
Show Gist options
  • Save kylpo/a3fef714f29a4534394cb00a36793d44 to your computer and use it in GitHub Desktop.
Save kylpo/a3fef714f29a4534394cb00a36793d44 to your computer and use it in GitHub Desktop.
import { pipe } from 'fp-ts/lib/pipeable'
import * as O from 'fp-ts/lib/Option'
import * as A from 'fp-ts/lib/Array'
import * as R from 'fp-ts/lib/Record'
// V1: First version that does a record lookup, then Option is unwrapped with a default [] to map over.
const data = R.lookup("someArray", someRecord)
.getOrElse([])
.map(toSomeTransformation)
// V2: versus of a more fp way(?) that will only map over the Some value of the Option lookup
const data = pipe(
R.lookup("someArray", someRecord),
O.map(
A.map(toSomeTransformation),
),
O.getOrElse([]),
)
// V2-alt: Maybe a not totally fair comparison though, since it used pipe() as well, so here's a version without pipe
const data = R.lookup("someArray", someRecord)
.map(A.map(toSomeTransformation))
.getOrElse([]),
)
// I'm not sure which version I like best yet. /shrug
// OR, just leave Option out of this..?
const someArray = someRecord.someArray
const data = someArray == null ? [] : someArray.map(toSomeTransformation)
// Previous example helped me see that a fold() may've been best
const data = pipe(
R.lookup("someArray", someRecord),
O.fold(
[],
someArray => someArray.map(toSomeTransformation)
)
)
// Hmm, yeah, last version with fold seems pretty nice...
@tdreyno
Copy link

tdreyno commented Jul 20, 2020

I'd probably go v1. In Elm:

data = someRecord
  |> Dict.get "someArray"
  |> Maybe.withDefault []
  |> List.map toSomeTransformation

@kylpo
Copy link
Author

kylpo commented Aug 4, 2020

@tdreyno Looks like v2 of fp-ts removed method chaining and requires pipe(). So, it makes the decision easy :).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment