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

Function shareObjectChecks

ark/aot/flat.ts:2137–2177  ·  view source on GitHub ↗
({ code, program }, s)

Source from the content-addressed store, hash-verified

2135// an Apply opens by checking data is an object, in a program of objects the text
2136// it most repeats. Hot on a rejected call, V8 inlines each call as it read the text
2137const shareObjectChecks: UnitsPass = ({ code, program }, s) => {
2138 // each with what it returns where it fails, if it's a statement returning
2139 const checks: [start: number, text: string, fails: string | undefined][] = []
2140 for (const statement of program.body as Node[]) {
2141 if (statement.type !== "VariableDeclaration") continue
2142 for (const { id, init } of statement.declarations) {
2143 if (
2144 !init ||
2145 !isFunctionExpression(init) ||
2146 !applyName.test((id as { name?: string }).name ?? "")
2147 )
2148 continue
2149 for (const check of code
2150 .slice(init.start, init.end)
2151 .matchAll(objectCheck))
2152 checks.push([init.start + check.index, check[0], check[1]])
2153 }
2154 }
2155 const isObject = nameFreeIn(code, "isObjectData")
2156 const notObject = nameFreeIn(code, "notObjectData")
2157 const fails = checks.find(check => check[2])?.[2]
2158 const helpers = `const ${isObject} = function (data) { return data instanceof Object || Object(data) === data }\n${
2159 fails ?
2160 `const ${notObject} = function (data, ctx) { return ${fails} }\n`
2161 : ""
2162 }`
2163 const calls = checks.map(([, , fails]) =>
2164 fails ?
2165 `if (!${isObject}(data)) return ${notObject}(data, ctx)`
2166 : `${isObject}(data)`
2167 )
2168 if (
2169 minifiedLengthOf(helpers + calls.join("")) >=
2170 minifiedLengthOf(checks.map(([, text]) => text).join(""))
2171 )
2172 return true
2173 for (const [i, [start, text]] of checks.entries())
2174 s.overwrite(start, start + text.length, calls[i])
2175 s.prependRight(0, helpers)
2176 return true
2177}
2178
2179// arrows are shorter than function expressions and gzip smaller, and V8 reads
2180// them in full where a function holds them. That costs about 47 instructions a

Callers

nothing calls this directly

Calls 7

minifiedLengthOfFunction · 0.90
isFunctionExpressionFunction · 0.85
nameFreeInFunction · 0.85
testMethod · 0.80
findMethod · 0.80
mapMethod · 0.65
pushMethod · 0.45

Tested by

no test coverage detected