Skip to content

Instantly share code, notes, and snippets.

@gcanti
Last active December 7, 2022 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcanti/81067cbacd5d3edf258f070f1b4dd627 to your computer and use it in GitHub Desktop.
Save gcanti/81067cbacd5d3edf258f070f1b4dd627 to your computer and use it in GitHub Desktop.
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