Created
October 15, 2020 16:02
-
-
Save Willmo36/f238e3225c235e5eb3701375aeadfb11 to your computer and use it in GitHub Desktop.
monocle-ts traversal example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as T from "monocle-ts/lib/Traversal"; | |
import * as R from "fp-ts/lib/Record"; | |
import { pipe } from "fp-ts/lib/function"; | |
import { Lens } from "monocle-ts"; | |
type Person = { | |
age: number; | |
hairColor: string; | |
}; | |
//normal Lens | |
const PersonL = Lens.fromProp<Person>(); | |
const HairColorL = PersonL("hairColor"); | |
/** | |
* Traverse all the Person in Record<string, Person> | |
* Reaching to the .hairColor via the Lens above | |
* only if the .page > 70 (this is the cool part) | |
*/ | |
const traverseRecordPerson = pipe( | |
T.fromTraversable(R.record)<Person>(), | |
T.filter((person) => person.age > 70), | |
T.compose(HairColorL.asTraversal()) | |
); | |
const setOldPplToWhiteHair = pipe( | |
traverseRecordPerson, | |
T.modify((hairColor) => "white") | |
); | |
const ppl: Record<string, Person> = { | |
david: { age: 71, hairColor: "brown" }, | |
max: { age: 26, hairColor: "brown" } | |
}; | |
const result = setOldPplToWhiteHair(ppl); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment