Last active
December 7, 2022 16:45
-
-
Save gcanti/81067cbacd5d3edf258f070f1b4dd627 to your computer and use it in GitHub Desktop.
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 { Option } from '@fp-ts/data/Option' | |
import * as O from '@fp-ts/data/Option' | |
import * as S from '@fp-ts/data/String' | |
import produce from 'immer' | |
import * as Optic from '@fp-ts/optic' | |
import * as StringOptic from '@fp-ts/optic/data/String' | |
import { pipe } from '@fp-ts/data/Function' | |
// let's say we want to uppercase the second item of the array | |
interface S { | |
readonly a: { | |
readonly b: Option<{ | |
readonly c: ReadonlyArray<Option<string>> | |
}> | |
} | |
} | |
const s: S = { | |
a: { | |
b: O.some({ | |
c: [O.none, O.some('aaa'), O.some('bbb')] | |
}) | |
} | |
} | |
const _c_1 = Optic.id<S>() | |
.at('a') | |
.at('b') | |
.some() | |
.at('c') | |
.index(1) | |
.some() | |
.compose(StringOptic.index(0)) | |
const withOptic = pipe(s, Optic.modify(_c_1)(S.toUpperCase)) | |
const withImmer = produce(s, (draft) => { | |
const b = draft.a.b | |
if (O.isSome(b)) { | |
if (b.value.c.length >= 2 && O.isSome(b.value.c[1])) { | |
const s = b.value.c[1].value | |
b.value.c[1] = O.some(S.toUpperCase(s.charAt(0)) + s.substring(1)) | |
} | |
} | |
}) | |
console.log(JSON.stringify(withOptic, null, 2)) | |
console.log(JSON.stringify(withImmer, null, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment