( ops: T, operator?: string, canonicalize = true )
| 15 | * Note: *not* recursive |
| 16 | */ |
| 17 | export 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. |
no test coverage detected