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

Function isTree

packages/effect/src/SchemaAST.ts:5362–5420  ·  view source on GitHub ↗
(u: unknown, isLeaf: (u: unknown) => boolean)

Source from the content-addressed store, hash-verified

5360}
5361
5362function isTree(u: unknown, isLeaf: (u: unknown) => boolean): boolean {
5363 const cache = new WeakMap<object, boolean>()
5364 const stack: Array<TreeFrame> = []
5365 outer: while (true) {
5366 if (typeof u !== "object" || u === null) {
5367 if (!isLeaf(u)) {
5368 return false
5369 }
5370 } else {
5371 const value = u
5372 const cached = cache.get(value)
5373 // `false` marks a node on the current path, while `true` marks a fully
5374 // validated node that can be safely reused by a DAG.
5375 if (cached === false) {
5376 return false
5377 }
5378 if (cached === undefined) {
5379 const isArray = Array.isArray(value)
5380 if (!isArray) {
5381 const prototype = Object.getPrototypeOf(value)
5382 // A plain object from another realm has a different Object.prototype,
5383 // but that prototype still has a null prototype.
5384 if (
5385 prototype !== null &&
5386 prototype !== Object.prototype &&
5387 Object.getPrototypeOf(prototype) !== null
5388 ) {
5389 return false
5390 }
5391 }
5392 cache.set(value, false)
5393 stack.push({
5394 value,
5395 keys: isArray ? value.length : Object.keys(value),
5396 index: 0
5397 })
5398 }
5399 }
5400
5401 while (stack.length > 0) {
5402 const frame = stack[stack.length - 1]
5403 const keys = frame.keys
5404 if (typeof keys === "number") {
5405 if (frame.index < keys) {
5406 // A sparse slot is read as `undefined`; the leaf predicate determines
5407 // whether that is valid for the current tree.
5408 u = (frame.value as ReadonlyArray<unknown>)[frame.index++]
5409 continue outer
5410 }
5411 } else if (frame.index < keys.length) {
5412 u = (frame.value as Record<string, unknown>)[keys[frame.index++]]
5413 continue outer
5414 }
5415 cache.set(frame.value, true)
5416 stack.pop()
5417 }
5418 return true
5419 }

Callers 2

isJsonFunction · 0.70
isStringTreeFunction · 0.70

Calls 4

keysMethod · 0.80
getMethod · 0.65
setMethod · 0.65
pushMethod · 0.65

Tested by

no test coverage detected