MCPcopy Create free account
hub / github.com/arktypeio/arktype / encodeUnion

Function encodeUnion

ark/schema/shared/codecs.ts:106–149  ·  view source on GitHub ↗
(
	inner: Union.Inner,
	tfs: readonly boolean[],
	$: BaseScope
)

Source from the content-addressed store, hash-verified

104}
105
106const encodeUnion = (
107 inner: Union.Inner,
108 tfs: readonly boolean[],
109 $: BaseScope
110): Union.Input => {
111 if (inner.ordered) {
112 return {
113 ...inner,
114 branches: sortByTfs(inner.branches, tfs),
115 ordered: true
116 }
117 }
118 const plain: BaseRoot[] = []
119 const morphed: BaseRoot[] = []
120 for (let i = 0; i < inner.branches.length; i++) {
121 const branch = inner.branches[i]
122 // a branch without morphs (like a plain branch, or one whose only
123 // transform was a default) encodes values unchanged
124 if (branch.hasAlias ? tfs[i] : branch.tfs) morphed.push(branch)
125 else plain.push(branch)
126 }
127 if (!plain.length) return { ...inner, branches: morphed }
128 if (!morphed.length) return inner
129 // validate transforming branches pairwise as an unordered union so
130 // overlapping codec outputs throw even alongside a plain branch
131 const morphedBranches =
132 morphed.length > 1 ?
133 $.node("union", { branches: morphed }).branches
134 : morphed
135 const overlapsPlain = plain.some(p =>
136 morphedBranches.some(m => p._in.overlaps(m._in))
137 )
138 if (!overlapsPlain || morphedBranches.every(b => b.deletesOnly))
139 return { ...inner, branches: [...plain, ...morphedBranches] }
140 const plainBranches =
141 plain.length > 1 ? $.node("union", { branches: plain }).branches : plain
142 return {
143 ...inner,
144 // a branch without morphs encodes a value unchanged, so try it before
145 // an overlapping codec branch
146 branches: [...plainBranches, ...morphedBranches],
147 ordered: true
148 }
149}
150
151const sortByTfs = (
152 branches: readonly BaseRoot[],

Callers 1

mapperFunction · 0.85

Calls 4

sortByTfsFunction · 0.85
nodeMethod · 0.80
overlapsMethod · 0.80
pushMethod · 0.45

Tested by

no test coverage detected