MCPcopy Create free account
hub / github.com/Effect-TS/effect / OptionalImpl

Class OptionalImpl

packages/effect/src/Optic.ts:980–1136  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

978export interface Traversal<in out S, in out A> extends Optional<S, ReadonlyArray<A>> {}
979
980class OptionalImpl<S, A> implements Optional<S, A> {
981 /** @internal */
982 readonly node: Node
983 readonly getResult: (s: S) => Result.Result<A, SchemaIssue.Issue>
984 readonly replaceResult: (a: A, s: S) => Result.Result<S, SchemaIssue.Issue>
985 constructor(
986 node: Node,
987 getResult: (s: S) => Result.Result<A, SchemaIssue.Issue>,
988 replaceResult: (a: A, s: S) => Result.Result<S, SchemaIssue.Issue>
989 ) {
990 this.node = node
991 this.getResult = getResult
992 this.replaceResult = replaceResult
993 }
994 replace(a: A, s: S): S {
995 return Result.getOrElse(this.replaceResult(a, s), () => s)
996 }
997 modify(f: (a: A) => A): (s: S) => S {
998 return (s) => Result.getOrElse(Result.flatMap(this.getResult(s), (a) => this.replaceResult(f(a), s)), () => s)
999 }
1000 compose(that: any): any {
1001 return make(compose(this.node, that.node))
1002 }
1003 key(key: PropertyKey): any {
1004 return make(compose(this.node, [new PathNode([key])]))
1005 }
1006 optionalKey(key: PropertyKey): any {
1007 return make(
1008 compose(
1009 this.node,
1010 primitiveNode(
1011 "Lens",
1012 (s) => s[key],
1013 (a, s) => {
1014 const copy = cloneShallow(s)
1015 if (a === undefined) {
1016 if (
1017 Array.isArray(copy) &&
1018 (typeof key === "number" || (typeof key === "string" && Arr.isCanonicalArrayIndex(key)))
1019 ) {
1020 copy.splice(Number(key), 1)
1021 } else {
1022 delete copy[key]
1023 }
1024 } else {
1025 InternalRecord.assignProperty(copy, key, a)
1026 }
1027 return copy
1028 }
1029 )
1030 )
1031 )
1032 }
1033 check(...checks: readonly [SchemaAST.Check<any>, ...Array<SchemaAST.Check<any>>]): any {
1034 return make(compose(this.node, [new CheckNode(checks)]))
1035 }
1036 refine<B extends A>(refinement: (a: A) => a is B, annotations?: Schema.Annotations.Filter): any {
1037 return make(compose(this.node, [new CheckNode([SchemaAST.makeFilterByGuard(refinement, annotations)])]))

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected