MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / flatten

Function flatten

src/compute-engine/boxed-expression/flatten.ts:17–69  ·  view source on GitHub ↗
(
  ops: T,
  operator?: string,
  canonicalize = true
)

Source from the content-addressed store, hash-verified

15 * Note: *not* recursive
16 */
17export function flatten<T extends ReadonlyArray<Expression> | Expression[]>(
18 ops: T,
19 operator?: string,
20 canonicalize = true
21): T {
22 // Optionally make all the arguments canonical.
23 const xs: ReadonlyArray<Expression> =
24 !canonicalize || ops.every((x) => x.isCanonical)
25 ? ops
26 : ops.map((x) => x.canonical);
27
28 if (operator) {
29 const shouldFlatten = (x: Expression) =>
30 isSymbol(x, 'Nothing') ||
31 x.operator === operator ||
32 x.operator === 'Sequence';
33
34 // Bypass memory allocation for the common case where there is nothing to flatten
35 if (xs.every((x) => !shouldFlatten(x))) return xs as T;
36
37 // Iterate over the list of expressions and flatten them
38 const ys: Expression[] = [];
39 for (const x of xs) {
40 // Skip Nothing
41 if (isSymbol(x, 'Nothing')) continue;
42
43 // If the operator matches, flatten the expression
44 if (
45 isFunction(x) &&
46 (x.operator === operator || x.operator === 'Sequence')
47 )
48 ys.push(...flatten(x.ops, operator, canonicalize));
49 else ys.push(x);
50 }
51 return ys as T;
52 }
53
54 if (xs.every((x) => !(isSymbol(x, 'Nothing') || x.operator === 'Sequence')))
55 return xs as T;
56
57 // Iterate over the list of expressions and flatten them
58 const ys: Expression[] = [];
59 for (const x of xs) {
60 // Skip Nothing
61 if (isSymbol(x, 'Nothing')) continue;
62
63 // If the operator matches, flatten the expression
64 if (isFunction(x, 'Sequence'))
65 ys.push(...flatten(x.ops, operator, canonicalize));
66 else ys.push(x);
67 }
68 return ys as T;
69}
70
71/**
72 * Like {@link flatten}, but ellipsis-fold barriers are held back.

Callers 15

sets.tsFile · 0.90
canonicalRelationalFunction · 0.90
core.tsFile · 0.90
arithmetic.tsFile · 0.90
evaluateMinMaxFunction · 0.90
canonicalAddFunction · 0.90
termsAsExpressionFunction · 0.90
holdMapFunction · 0.90
holdMapAsyncFunction · 0.90
makeCanonicalFunctionFunction · 0.90
checkArityFunction · 0.90
checkNumericArgsFunction · 0.90

Calls 4

isSymbolFunction · 0.90
isFunctionFunction · 0.90
shouldFlattenFunction · 0.85
mapMethod · 0.65

Tested by

no test coverage detected