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

Function writeIntersectionExpression

ark/schema/roots/intersection.ts:461–528  ·  view source on GitHub ↗
(node: Intersection.Node)

Source from the content-addressed store, hash-verified

459}
460
461const writeIntersectionExpression = (node: Intersection.Node) => {
462 const basis = writtenBasisOf(node)
463 // an operand has at most one right comparator, so a second != is an operand of its own
464 let preStruct = writtenPrestructuralsOf(node)
465 let excluded = preStruct.filter(isNotEqual)
466 if (excluded.length) {
467 preStruct = preStruct.filter(n => !isNotEqual(n))
468 if (!preStruct.some(isComparator)) {
469 preStruct = [...preStruct, excluded[0]]
470 excluded = excluded.slice(1)
471 }
472 }
473
474 // a keyword's predicate has no syntax but its keyword, written in place of the children it holds
475 const { keywords, written } = keywordsOf(node)
476 preStruct = preStruct.filter(n => !written.has(n))
477
478 const basisExpression =
479 keywords.length ? keywords.join(" & ")
480 : basis && !node.preStruct.some(n => n.impl.coversExpr) ? basis.nestedExpr
481 : ""
482
483 // a range is written as it's parsed, e.g. `1 <= number <= 5`
484 const upper = preStruct.find(n => isLimit(n, "upper"))
485 const lower = upper && preStruct.find(n => isLimit(n, "lower"))
486
487 // a pattern is an operand of its own, and other refinements follow theirs
488 const refinementsExpression = preStruct
489 .filter(n => !lower || (n !== lower && n !== upper))
490 .map(
491 (n, i) =>
492 (i === 0 && !basisExpression ? ""
493 : n.kind === "pattern" ? " & "
494 : " ") + n.expression
495 )
496 .join("")
497
498 const fullExpression =
499 basisExpression === "Array" && refinementsExpression === " == 0" ?
500 "[]"
501 : `${basisExpression}${refinementsExpression}`
502
503 let expression =
504 node.structure && !written.has(node.structure) ?
505 fullExpression ?
506 `${node.structure.expression}${basis ? " & " : " "}${fullExpression}`
507 : node.structure.expression
508 : fullExpression
509
510 if (lower) {
511 const limit = lower.expression.slice(lower.comparator.length + 1)
512 // what it bounds is grouped if it intersects patterns
513 const operand = expression.includes(" & ") ? `(${expression})` : expression
514 expression = `${limit} ${lower.comparator === ">" ? "<" : "<="} ${operand} ${upper.expression}`
515 }
516
517 // a case a union discriminates by domain has no basis of its own
518 for (const n of excluded)

Callers 1

expressionMethod · 0.85

Calls 9

writtenBasisOfFunction · 0.85
writtenPrestructuralsOfFunction · 0.85
isNotEqualFunction · 0.85
isLimitFunction · 0.85
filterMethod · 0.80
findMethod · 0.80
keywordsOfFunction · 0.70
mapMethod · 0.65
hasMethod · 0.45

Tested by

no test coverage detected