Expression
Represents a symbolic expression in Nerdamer's canonical expression tree.
Expression is the central symbolic value type used by the parser and by the
algebra, calculus, and solver layers. Parsed expressions are normalized into a
small set of internal node categories such as numbers, variables, functions,
powers, products, and sums. Numeric coefficients are normally stored in a
Rational multiplier rather than as separate product elements.
Most arithmetic and transformation methods return a new Expression, but the
class itself is mutable because parser and algorithm internals rebuild nodes in
place. Accessors such as Expression.getArguments,
Expression.getMultiplier, and Expression.getPower may lazily
initialize and return internal objects. Use Expression.copy when an
independently mutable expression tree is required.
Expression.create is the preferred construction API for ordinary
expression construction and coercion. It centralizes supported input handling and
normalization. When the input is already an Expression, it preserves object
identity unless its copy argument is set to true.
When the source is already known to be an Expression and an independent tree is
required, use Expression.copy. When a caller accepts broader input but must
guarantee a clone for an existing expression, use
Expression.create(input, undefined, true).
Direct new Expression(...) construction is reserved for representation-level
internals that require constructor semantics, such as the plainConstruct path and
the implementation of Expression.copy. Ordinary callers should not use the
constructor for coercion or cloning.
The internal expression groups are organizational categories used by Nerdamer's
canonicalization logic. They should not be confused with general mathematical
classifications:
- NUM stores plain numeric values.
- VAR stores symbols/variables whose powers fit the variable representation.
- EXP stores bases with powers that require a separate exponential node; it is
not the same thing as an exponential function.
- FUN stores function calls.
- GRP stores sums with a common base but differing powers, such as
x + x^y or cos(x) - 3*cos(x)^2.
- PRD stores products of non-numeric symbolic factors; numeric coefficients are
moved to the outer multiplier during parsing.
- SUM stores other sums. For example, 1 + x + x^2 is a SUM containing a
numeric term and a grouped polynomial-like component.
- INF stores infinite values.
Examples
const expression = Expression.create('2*x + 1');
expression.text(); // "1+2*x"
expression.evaluate({ x: 3 }).text(); // "7"Members
abs(): ExpressionMethodReturns the symbolic absolute value of this expression.
The operation delegates to Nerdamer's abs implementation and may simplify
values whose sign or complex magnitude can be determined.
Returns
Expression — The resulting expression; the receiver is not modified.
Examples
Expression.create(-5).abs().text(); // "5"
Expression.create('x').abs().text(); // "abs(x)"add(x: ExpressionInput): ExpressionMethodLegacy alias for plus.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The value to add. |
Returns
Expression — A new Expression representing this + x.
args: Expression[]PropertyArguments stored by a function node. Prefer Expression.getArguments when consuming this representation.
base: ExpressionPropertyExplicit mathematical base stored by an EXP node.
Non-EXP nodes derive their base through Expression.getBase instead.
buildFunction(args?: string[]): (...args: number[]): numberMethodCompiles this expression into a native JavaScript numeric function.
The generated function uses JavaScript number arithmetic and the registered
numerical implementations. It is intended for repeated, relatively low-precision
scalar evaluation rather than arbitrary-precision symbolic computation. Functions
without a faithful JavaScript-number equivalent are rejected instead of being
compiled with approximate or unrelated semantics.
When args is omitted, free variables are collected and sorted alphabetically.
Supplying args defines the positional argument order explicitly.
core!UnsupportedOperationError If a surviving function has no faithful JavaScript-number implementation.
Parameters
| Name | Type | Description |
|---|---|---|
args | string[] | Variable names in the positional order expected by the compiled function. |
Returns
(...args: number[]): number — A JavaScript function accepting numeric arguments and returning a number.
Examples
const fn = Expression.create('x^2 + y').buildFunction(['x', 'y']);
fn(3, 1); // 10coeffs(...variables: string[]): CoeffObjectMethodCollects coefficients with respect to one or more requested variables.
The expression is expanded as part of coefficient collection. For multivariate
input, coefficient keys encode the exponent tuple in the same order as
variables. Terms that do not contain a requested variable are retained as
coefficients rather than discarded.
Parameters
| Name | Type | Description |
|---|---|---|
variables | string[] | Variables whose powers define the coefficient keys. |
Returns
CoeffObject — Nerdamer's coefficient object for the requested variable ordering.
Examples
const coefficients = Expression.create('3*x^2 + 2*x + 1').coeffs('x');
coefficients.toArray().map(value => value.text()); // ["1", "2", "3"]Expression(x: NerdamerInput, plainConstruct?: boolean): ExpressionConstructorConstructs or copies an expression value.
Direct construction is primarily a representation-level API. When x is an
existing Expression, the constructor deep-copies its expression tree. When
plainConstruct is true and x is a string, that string is stored as the
raw node value without parsing. Other inputs are delegated to
Expression.create, and JavaScript constructor return semantics therefore
allow that factory-created expression to become the result of new Expression(...).
Ordinary code should use Expression.create for construction/coercion and
Expression.copy when an independent tree is required. Direct constructor
calls are reserved for low-level representation code.
Parameters
| Name | Type | Description |
|---|---|---|
x | NerdamerInput | The expression or Nerdamer input used to construct the value. |
plainConstruct | boolean | Store a string as a raw internal value instead of parsing it. |
Returns
copy(): ExpressionMethodDeep-copies the expression tree.
Multipliers, powers, function arguments, explicit exponential bases, and aggregate elements are recursively copied. Mutating those structures on the returned expression therefore does not mutate the corresponding structures on the source.
Returns
Expression — An independently mutable expression with the same symbolic representation.
Examples
const source = Expression.create('x + 1');
const copy = source.copy();
copy === source; // false
copy.text(); // "1+x"create(x: NerdamerInput, values?: ParserValuesObject, copy?: boolean): ExpressionMethodConverts supported Nerdamer input into an Expression.
Strings and primitive numeric inputs are parsed through Parser. An
existing Expression is returned unchanged when no substitution values are
supplied; pass copy: true to request an independent deep copy. A
Rational is converted to a numeric expression while preserving its
decimal-origin marker.
An Equation is converted to its residual expression by moving the right
side to the left on a copy of the equation. For example, x = 2 becomes the
expression x - 2 in canonical form.
core!UnexpectedDataType
Thrown when parsing produces another parser entity, such as a vector or matrix,
where an Expression is required.
Parameters
| Name | Type | Description |
|---|---|---|
x | NerdamerInput | The expression-compatible input to convert. |
values | ParserValuesObject | Parser substitutions applied while parsing non-Expression input. |
copy | boolean | Copy an existing Expression instead of preserving its identity. |
Returns
Expression — The parsed, converted, reused, or copied expression.
Examples
const expression = Expression.create('x^2 + 1');
Expression.create(expression) === expression; // true
Expression.create(expression, undefined, true) === expression; // false
Expression.create('a+b', { a: 2, b: 3 }).text(); // "5"dataType: stringPropertyParser entity discriminator for expression values.
deferred: booleanPropertySignals that the Expression was parsed with the deferred flag true
denominator(): ExpressionMethodLegacy alias for getDenominator.
Returns
Expression — The denominator Expression.
diff(variable?: ExpressionInput, n?: number | Expression): ExpressionMethodDifferentiates this expression symbolically.
Parameters
| Name | Type | Description |
|---|---|---|
variable | ExpressionInput | Variable to differentiate with respect to. When omitted, the derivative implementation selects the first variable present in the expression. |
n | number | Expression | Derivative order. The derivative implementation uses first order when omitted. |
Returns
Expression — The symbolic derivative; the receiver is not modified.
DISTRIBUTE_MULTIPLIER: booleanPropertyControls whether addition first distributes an outer multiplier on a sum.
This is a process-wide parser/algebra setting used by the addition operation. Changing it affects subsequent symbolic operations globally.
distributeMultiplier(): ExpressionMethodDistributes this node's outer multiplier through a linear sum.
A copy is created before any changes are made. Distribution is performed only when the expression is sum-like, has power one, and carries a non-unit outer multiplier. Nested sum terms encountered during the pass are handled recursively. Expressions that do not meet those conditions are returned as equivalent copies.
Returns
Expression — A new expression with the eligible multiplier distributed.
Examples
Expression.create('2*(x+y)').distributeMultiplier().text(); // "2*x+2*y"div(x: ExpressionInput): ExpressionMethodDivides this Expression by the given value.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The divisor. |
Returns
Expression — A new Expression representing this / x.
Examples
Expression.create('x^2').div('x').text() // "x"
Expression.create(10).div(3).text() // "10/3"divide(x: ExpressionInput): ExpressionMethodLegacy alias for div.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The divisor. |
Returns
Expression — A new Expression representing this / x.
E(asNumericValue?: boolean): ExpressionMethodCreates Euler's constant as a symbolic or evaluated expression.
Parameters
| Name | Type | Description |
|---|---|---|
asNumericValue | boolean | Force the evaluated representation even when parser evaluation mode is disabled. |
Returns
Expression — Symbolic e, or its current numeric representation when evaluation is enabled.
Examples
Expression.E().text(); // "e"
Expression.E(true).text(); // numeric approximationeach(fn: (a: Expression, b: string | number): void | Expression): ExpressionMethodVisits the immediate terms represented by this expression.
Aggregate nodes pass each stored element and its key to fn. Atomic nodes invoke
the callback once with a unit-multiplier form of the expression and the node's
value as the key. The callback's return value is ignored; this method does not
rebuild the expression. Use Expression.forEveryElement when returned
replacements should participate in reconstruction.
For atomic nodes, creating the unit-multiplier argument does not mutate the receiver.
Aggregate elements, however, are passed by reference, so the callback can mutate
their internal objects if it chooses to do so.
Parameters
| Name | Type | Description |
|---|---|---|
fn | (a: Expression, b: string | number): void | Expression | Visitor receiving an immediate expression element and its key. |
Returns
Expression — This expression for chaining.
elements: Record<string, Expression>PropertyCanonically keyed child expressions for aggregate nodes such as sums and products.
The record is mutable representation state. Expression.getElements returns this object directly when it exists; callers that mutate it are responsible for preserving a valid expression representation and regenerating derived values.
elementsArray(withMultiplier?: boolean): Expression[]MethodReturns the immediate expression elements in canonical sort order.
Sum-like nodes flatten nested linear sums one level while products retain nested
sums. Atomic nodes contribute a unit-multiplier copy. When withMultiplier is
true, a product's outer multiplier is appended as a numeric expression before
sorting. The option has no effect on sums.
Stored aggregate elements are returned by reference rather than deep-copied.
Parameters
| Name | Type | Description |
|---|---|---|
withMultiplier | boolean | Include a product's outer coefficient as an array element. |
Returns
Expression[] — The sorted immediate elements.
eq(x: string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational): booleanMethodTests whether this expression is symbolically equal to another value.
Equality is not a JavaScript identity or raw-tree comparison. Nerdamer first
consults applicable assumptions and otherwise subtracts the expressions,
canonicalizes numeric radicals where needed, expands the difference, and accepts
equality when that result reduces to numeric zero. A false result therefore
means equality was not established by the current comparison machinery; it is
not a general theorem-prover result for arbitrary symbolic identities.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational | Value to compare with this expression. |
Returns
boolean — true when Nerdamer establishes equality, otherwise false.
Examples
Expression.create('x+1').eq('1+x'); // true
Expression.create(3).eq(4); // falseequals(value: ExpressionInput): EquationMethodCreates an equation with this expression on the left-hand side.
Parameters
| Name | Type | Description |
|---|---|---|
value | ExpressionInput | — |
Returns
evaluate(values?: ParserValuesObject): ExpressionMethodRe-evaluates this expression numerically, optionally substituting variable values.
Evaluation uses the ordinary serialization path. When scientific display metadata is present, a copy without that metadata is serialized so formatting cannot change the value sent through Parser.evaluate. That parser path enables Nerdamer's evaluation mode, so numeric constants and supported numeric functions are evaluated according to the parser's current precision and settings. The original expression is not modified.
Parameters
| Name | Type | Description |
|---|---|---|
values | ParserValuesObject | Variable substitutions applied during evaluation. |
Returns
Expression — The evaluated expression.
Examples
Expression.create('x^2 + 1').evaluate({ x: 3 }).text(); // "10"
Expression.create('pi/2').evaluate().text(); // numeric approximationexpand(): ExpressionMethodExpands products and eligible powers into an equivalent symbolic expression.
Expansion delegates to Nerdamer's canonical expansion algorithm. The result is independent of the receiver, but callers should treat object identity as an implementation detail rather than relying on expansion to allocate a particular representation. Branch-sensitive power rules are preserved rather than treating every algebraic power identity as universally valid over the complex domain.
Returns
Expression — The expanded expression.
Examples
Expression.create('(x+1)^2').expand().text(); // "1+2*x+x^2"factor(): ExpressionMethodNo description is available yet.
Returns
forEveryElement(fn: (x: Expression): Expression): ExpressionMethodApplies a transformation while recursively rebuilding this expression.
Unlike Expression.each, callback results are used as replacements. The
traversal reconstructs functions, products, sums, and exponential powers while
restoring the original outer multiplier and power. Numeric and variable roots are
returned unchanged by the traversal helper rather than passed through fn, so the
result may preserve the receiver's identity for those atomic cases.
Parameters
| Name | Type | Description |
|---|---|---|
fn | (x: Expression): Expression | Transformation applied to traversed symbolic components. |
Returns
Expression — The rebuilt expression.
fromRational(x: Rational): ExpressionMethodConverts a rational value into a numeric expression.
The conversion preserves the rational's asDecimal provenance flag so later
formatting and decimal-contagion logic can distinguish decimal-origin values.
Parameters
| Name | Type | Description |
|---|---|---|
x | Rational | Rational value to convert. |
Returns
Expression — A new numeric expression with an independent multiplier.
Examples
const rational = Rational.create('3/4');
Expression.fromRational(rational).text(); // "3/4"Function(x: string): ExpressionMethodCreates a symbolic function node with the given name. This creates a bare function symbol without arguments. To create a function with arguments, use Expression.toFunction instead.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | The function name. |
Returns
Expression — A function-typed Expression.
Examples
Expression.Function('f').text() // "f"functions(fns?: string[], getValues?: boolean): string[]MethodCollects distinct function occurrences from the expression tree.
By default the returned strings are function names such as sin and cos.
When getValues is true, the collector instead returns each function node's
stored value string, such as sin(x), while still deduplicating repeated values.
Traversal includes function arguments, aggregate elements, and EXP bases and
powers.
If fns is supplied, results are appended to that same array.
Parameters
| Name | Type | Description |
|---|---|---|
fns | string[] | Optional accumulator that receives unique strings. |
getValues | boolean | Collect stored function-expression strings instead of names. |
Returns
string[] — The accumulator containing the collected function strings.
Examples
Expression.create('sin(x) + cos(y)').functions(); // ["sin", "cos"]getArguments(): Expression[]MethodReturns the mutable argument array stored by this function node.
The array is lazily created when no arguments are present and is returned by
reference, not copied. Mutating the returned array therefore mutates this
expression. Call Expression.updateValue after structural changes when
the stored value string must be regenerated.
Returns
Expression[] — The internal function-argument array.
Examples
Expression.create('sin(x)').getArguments()[0].text(); // "x"getBase(): ExpressionMethodReturns the mathematical base represented by this node.
EXP nodes return their stored base directly because signs and coefficients that
belong inside an exponential base must remain part of that base. Other node types
derive the same base from a deep structural copy with the outer multiplier and
outer power removed.
The EXP branch returns the internal base by reference. The non-EXP branch
returns an independent expression and does not re-enter the parser.
Returns
Expression — The stored or derived base expression.
Examples
Expression.create('3*x^2').getBase().text(); // "x"
Expression.create('2^(x+1)').getBase().text(); // "2"getDenominator(): ExpressionMethodExtracts the denominator represented by this expression's current structure.
The operation collects the rational multiplier's denominator and factors carried
by negative powers in a product. It does not first combine a sum over a common
denominator. For example, a/x + 8 is a sum whose outer denominator is one, while
the individual term a/x has denominator x.
Returns
Expression — The denominator represented by the current expression structure.
Examples
Expression.create('x/y').getDenominator().text() // "y"
Expression.create('3/4').getDenominator().text() // "4"getElements(): Record<string, Expression>MethodReturns the mutable child-element record stored by an aggregate expression.
When elements exists, the actual internal record is returned rather than a copy.
Mutating it therefore mutates this expression and can invalidate canonical keys or
the stored value string unless the caller restores the corresponding representation state. When this
node has no element record, a new empty object is returned and is not attached to
the expression.
Returns
Record<string, Expression> — The internal element record, or a detached empty record for atomic nodes.
getMultiplier(asExpression: true): ExpressionMethodReturns this node's effective outer rational multiplier.
The multiplier is initialized lazily. Numeric nodes derive it from their stored
value; other nodes default to one. Without asExpression, the returned
Rational is the actual mutable multiplier owned by this expression, not a
copy. Passing true wraps that rational value in a new numeric Expression.
Parameters
| Name | Type | Description |
|---|---|---|
asExpression | true | Return the coefficient as a numeric expression instead of a rational. |
Returns
Expression — The internal multiplier, or a numeric expression representing it.
Examples
Expression.create('3*x').getMultiplier().text(); // "3"
Expression.create('3*x').getMultiplier(true).text(); // "3"getNumerator(): ExpressionMethodExtracts the numerator represented by this expression's current structure.
The operation separates the numerator of the rational multiplier and recursively
collects numerator factors from linear products. It does not first rewrite a sum
over a common denominator; a sum such as a/x + 8 therefore remains the numerator
of that top-level representation.
Returns
Expression — The numerator represented by the current expression structure.
Examples
Expression.create('x/y').getNumerator().text() // "x"
Expression.create('3/4').getNumerator().text() // "3"getPower(): ExpressionMethodReturns this node's effective outer power.
The power is initialized lazily and stored on the expression. Numeric (NUM)
nodes default to power zero because their numeric value is carried by the
multiplier; other node types default to power one. The returned Expression is
the mutable internal power object, not a copy.
Returns
Expression — The internal power expression.
Examples
Expression.create('x^3').getPower().text(); // "3"
Expression.create('x').getPower().text(); // "1"getValue(arr: Expression[], f: "text" | "idString" | "keyValue", expressionType: number): stringMethodGenerates a canonical string representation for an array of sub-expressions,
joined by + (for SUM/GRP) or * (for PRD), with sums wrapped in parentheses
when inside a product.
Parameters
| Name | Type | Description |
|---|---|---|
arr | Expression[] | The array of sub-expressions. |
f | "text" | "idString" | "keyValue" | The string method to call on each element: 'idString', 'keyValue', or 'text'. |
expressionType | number | The parent expression type (SUM, GRP, or PRD). |
Returns
string — The joined string representation.
getVariable(variable: string): ExpressionMethodRetrieves a matching variable factor from this node.
The method returns this expression when its stored value matches variable, or
the matching immediate factor when this is a product. When no match is found it
returns the numeric zero expression rather than undefined.
Parameters
| Name | Type | Description |
|---|---|---|
variable | string | Stored variable value to locate. |
Returns
Expression — The matching expression reference, or zero when no match exists.
gt(x: string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational): booleanMethodTests whether this expression is > another value.
Nerdamer consults applicable assumptions and otherwise evaluates the difference
numerically/symbolically. These Expression comparison methods remain boolean for
compatibility. An unknown assumption result falls through to the ordinary comparison
path; if the relation still cannot be established, the method returns false. The
lower-level Assumption relations preserve unknown as undefined. Complex values are
not ordered and cause the comparison to throw.
core!UnsupportedOperationError Thrown when either side is classified as complex.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational | Value to compare with this expression. |
Returns
boolean — true when the requested ordering is established, otherwise false.
gte(x: string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational): booleanMethodTests whether this expression is >= another value.
Nerdamer consults applicable assumptions and otherwise evaluates the difference
numerically/symbolically. These Expression comparison methods remain boolean for
compatibility. An unknown assumption result falls through to the ordinary comparison
path; if the relation still cannot be established, the method returns false. The
lower-level Assumption relations preserve unknown as undefined. Complex values are
not ordered and cause the comparison to throw.
core!UnsupportedOperationError Thrown when either side is classified as complex.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational | Value to compare with this expression. |
Returns
boolean — true when the requested ordering is established, otherwise false.
hasDecimal(): booleanMethodReports whether decimal-origin numeric data occurs anywhere in this expression.
The check follows the multiplier, explicit power, exponential base, function
arguments, and aggregate elements. It tests the rational asDecimal provenance
marker; it does not merely search rendered text for a decimal point.
Returns
boolean — true when any contained rational originated from decimal input.
hasFunction(name: string, deep: boolean): booleanMethodTests whether a named function occurs in this expression.
Aggregate elements are always searched. When deep is true, function arguments
and the explicit base and power of EXP nodes are searched recursively as well.
With deep disabled, nested function arguments and EXP components are not
traversed.
Parameters
| Name | Type | Description |
|---|---|---|
name | string | Function name to locate. |
deep | boolean | Include function arguments and EXP base/power traversal. |
Returns
boolean — true when the named function is found.
hasIntegral(): booleanMethodReturns whether this expression contains an integral.
Returns
boolean
hasRadical(checkIrrationalDenominator?: boolean): booleanMethodTests the node's outer power for a rational exponent with a non-unit denominator.
This predicate examines this node's effective power; it does not recursively scan
every descendant for radicals. When checkIrrationalDenominator is true, the
power must also be negative, which identifies a radical occurring in a denominator.
Parameters
| Name | Type | Description |
|---|---|---|
checkIrrationalDenominator | boolean | Require the fractional power to be negative. |
Returns
boolean — true when the outer power meets the requested radical condition.
hasVariable(variable: string): booleanMethodTests whether a variable node with the requested value occurs in the expression tree.
Function arguments, aggregate elements, and EXP bases and powers are searched
recursively. This predicate does not apply the free-variable filtering used by
Expression.variables; reserved constants can still match when requested
explicitly.
Parameters
| Name | Type | Description |
|---|---|---|
variable | string | Variable value to locate. |
Returns
boolean — true when a matching VAR node occurs.
hook(x: NerdamerInput): NerdamerInputMethodIntercepts values passed through the Expression constructor.
The default implementation is the identity function. Applications may replace this static hook, but doing so changes direct-construction behavior globally. Expression.create does not route every parsed input through this hook.
Parameters
| Name | Type | Description |
|---|---|---|
x | NerdamerInput | Raw constructor input. |
Returns
NerdamerInput — The value the constructor should continue processing.
i(): ExpressionMethodMultiplies this Expression by the imaginary unit, converting it to an imaginary value.
Returns
Expression — A new Expression equal to this * i.
Examples
Expression.create(3).i().text() // "3*i"idString(): stringMethodReturns a string representation used internally for structural comparison of expressions.
Returns
string — A string identifier suitable for equality checks.
imaginary: stringPropertyThe symbol currently reserved for the imaginary unit. Use Parser.setI to change the symbol so the parser's restricted-name bookkeeping is updated at the same time.
imagPart(): ExpressionMethodReturns Nerdamer's symbolic decomposition of the imaginary component.
The result excludes the imaginary-unit factor itself. Decomposition follows
principal-branch handling for powered complex values and preserves unresolved
complex function components symbolically instead of silently treating them as
zero. realpart(...) and imagpart(...) nodes are treated as real-valued component
expressions.
Returns
Expression — The symbolic imaginary coefficient.
Img(): ExpressionMethodCreates the variable node representing the current imaginary-unit symbol.
Parser.setI
Returns
Expression — A new variable expression using Expression.imaginary.
Examples
Expression.Img().text(); // "i" with the default parser configurationInf(): ExpressionMethodCreates a symbolic positive infinity Expression.
Returns
Expression — An Expression representing +∞.
Examples
Expression.Inf().text() // "Infinity"integrate(variable?: ExpressionInput): ExpressionMethodNo description is available yet.
Parameters
| Name | Type | Description |
|---|---|---|
variable | ExpressionInput | — |
Returns
invert(): ExpressionMethodReturns the multiplicative inverse of this expression.
Real symbolic nodes are copied and inverted by negating the outer power and rational multiplier. Complex expressions use the general division path so real and imaginary components are handled correctly. Simple radical denominators are rationalized when the power operation identifies an eligible radical. The receiver is not modified.
core!DivisionByZeroError Thrown by the underlying rational or division operation when the expression is zero.
Returns
Expression — The reciprocal expression.
isComplex(): booleanMethodReports whether the current expression tree contains a complex-valued component.
The check is structural: it recognizes the current imaginary-unit symbol, recurses
through function arguments, EXP bases and powers, and aggregate elements. The
component functions realpart(...) and imagpart(...) are treated as real-valued
by definition even when their arguments contain complex values.
This predicate does not impose an ordering or otherwise claim that an unrestricted
symbolic expression is provably real.
Returns
boolean — true when the represented expression contains a recognized complex component.
isComplexComponentFunction(): booleanMethodTests whether this node is realpart(...) or imagpart(...).
These component functions are treated as real-valued by the complex-decomposition
logic even when their arguments are complex.
Returns
boolean
isConstant(): booleanMethodTests whether this node belongs to Nerdamer's currently recognized constant forms.
This is narrower than the mathematical statement "contains no free
variables." It recognizes numeric nodes, parser constants such as pi and e,
constant-base/constant-power EXP nodes, and sums or products whose elements are
recursively recognized as constant. The imaginary unit is handled by
dedicated complex logic rather than classified here as a parser constant.
Do not use this predicate as a general proof that an arbitrary function expression
is or is not mathematically constant.
Returns
boolean — true for the constant forms recognized by this predicate.
isE(): booleanMethodTests whether this node's stored value is the Euler-constant symbol e.
The check is representation-level and does not require a unit multiplier or power.
Returns
boolean — true when value is the current e symbol.
isEnumerable: booleanPropertyLet's the parser know not to treat it as a set of values
isEven(): booleanMethodChecks whether this Expression is an even integer.
Returns
boolean — true if the expression is NUM and its multiplier is even.
Examples
Expression.create(4).isEven() // true
Expression.create(3).isEven() // falseisEXP(): thisMethodChecks whether this Expression has the EXP (exponential/power) internal type.
Returns
this — true if the type is EXP.
isExpression(obj: unknown): objMethodType guard that checks whether an object is an Expression.
Parameters
| Name | Type | Description |
|---|---|---|
obj | unknown | The value to test. |
Returns
obj — true if obj is an Expression instance.
Examples
Expression.isExpression(Expression.create('x')) // true
Expression.isExpression(42) // falseisExpressionArray(obj: unknown): objMethodType guard that checks whether every element of an array is an Expression.
Parameters
| Name | Type | Description |
|---|---|---|
obj | unknown | The value to test. |
Returns
obj — true if obj is an array and all elements are Expressions.
isFraction(): booleanMethodReturns whether this expression's numeric multiplier is fractional.
Returns
boolean
isFunction(): thisMethodChecks whether this Expression is a function node.
Parameters
| Name | Type | Description |
|---|---|---|
names | string | string[] | A single function name or an array of names to match. |
Returns
this — true if the expression is a function node.
Examples
Expression.create('sin(x)').isFunction() // true
Expression.create('x').isFunction() // falseisHalf(): booleanMethodChecks whether this Expression is exactly 1/2.
Returns
boolean — true if the expression is the numeric value 1/2.
isI(): booleanMethodTests whether this node's stored value is the current imaginary-unit symbol.
This is a representation-level symbol check. It does not require the node to have
multiplier one or power one, so callers that require exactly the mathematical unit
i must impose those additional conditions themselves.
Returns
boolean — true when value matches Expression.imaginary.
isImaginary(): booleanMethodEvaluates the expression and reports whether the result is classified as complex.
Despite the historical method name, this is not a test for a purely imaginary
value with zero real part. A value such as 3 + 2*i also returns true because
the evaluated result contains a complex component.
Returns
boolean — true when the evaluated expression satisfies Expression.isComplex.
isInf(): booleanMethodChecks whether this Expression represents infinity (positive or negative).
Returns
boolean — true if the type is INF.
isInfinity(): booleanMethodLegacy alias for Expression.isInf.
Returns
boolean
isInteger(): booleanMethodChecks whether this Expression is an exact integer.
Returns
boolean — true if the expression is NUM with an integer multiplier.
Examples
Expression.create(5).isInteger() // true
Expression.create('3/2').isInteger() // falseisLinear(): booleanMethodChecks whether this Expression has power equal to 1 (i.e. is linear in itself).
Returns
boolean — true if the power is 1.
isMinusOne(): booleanMethodChecks whether this Expression is exactly -1.
Returns
boolean — true if the expression equals -1.
isNearlyZero(k: number): booleanMethodTests whether both evaluated complex components are small relative to Decimal precision.
The tolerance is 10^(-Decimal.precision + k). This is a numerical-algorithm
convenience and must not be used as a replacement for exact symbolic zero testing;
use Expression.isZero when exact representation-level zero is required.
Parameters
| Name | Type | Description |
|---|---|---|
k | number | Number of guard digits removed from the active Decimal precision. |
Returns
boolean — true when the magnitudes of both real and imaginary components are within the tolerance.
isNegative(): booleanMethodTests whether this expression is established to be strictly less than zero.
The result follows Expression.lt: unresolved symbolic sign information
currently produces false, while complex values cannot be ordered.
core!UnsupportedOperationError Thrown when the expression is classified as complex.
Returns
boolean — true when the current comparison machinery establishes a negative value.
isNegInf(): booleanMethodChecks whether this Expression is negative infinity (−∞).
Returns
boolean — true if the expression is −∞.
isNUM(): booleanMethodChecks whether this Expression has the NUM (numeric) internal type.
This only matches explicit numbers, not symbolic constants like pi or e.
Use isConstant to check for all values that reduce to a constant.
Returns
boolean — true if the type is NUM.
Examples
Expression.create(5).isNUM() // true
Expression.create('pi').isNUM() // falseisNumber(): booleanMethodTests whether this Expression is represented as a plain numeric value.
Returns
boolean — true for NUM expressions.
isOdd(): booleanMethodChecks whether this Expression is an odd integer.
Returns
boolean — true only for numeric integer expressions whose multiplier is odd.
isOne(): booleanMethodChecks whether this Expression is exactly 1.
Returns
boolean — true if the expression equals 1.
isPi(): booleanMethodTests whether this node's stored value matches a recognized π symbol. The check is representation-level and does not require a unit multiplier or power.
Returns
boolean — true when value is one of Nerdamer's π aliases.
isPlainVariable(): booleanMethodChecks whether this Expression is a plain variable with no multiplier and
no power (i.e. multiplier 1, power 1, type VAR).
Returns
boolean — true for a bare variable like x.
Examples
Expression.create('x').isPlainVariable() // true
Expression.create('2*x').isPlainVariable() // false
Expression.create('x^2').isPlainVariable() // falseisPolynomialLike(): booleanMethodTests whether this expression has the structural form of a polynomial over rational coefficients.
The predicate accepts recursively composed sums and products whose outer powers are
non-negative integers. Function nodes, EXP nodes, infinities, negative powers,
and fractional powers are rejected. This is a structural eligibility check used by
polynomial-oriented algorithms; it does not construct a algebra!Polynomial.
Returns
boolean — true when the expression satisfies the current polynomial-like restrictions.
isPosInf(): booleanMethodChecks whether this Expression is positive infinity (+∞).
Returns
boolean — true if the expression is +∞.
isProduct(): booleanMethodChecks whether this Expression has the PRD (product) internal type.
Returns
boolean — true if the type is PRD.
isQuarter(): booleanMethodChecks whether this Expression is exactly 1/4.
Returns
boolean — true if the expression is the numeric value 1/4.
isSum(): booleanMethodChecks whether this Expression is a summation-like type (SUM or GRP).
Returns
boolean — true if the type is SUM or GRP.
isVAR(): booleanMethodChecks whether this Expression has the VAR (variable) internal type.
Returns
boolean — true if the type is VAR.
isZero(): booleanMethodChecks whether this Expression is exactly 0.
Returns
boolean — true if the multiplier is zero.
Examples
Expression.create(0).isZero() // true
Expression.create(1).isZero() // falsekeyValue(asSubExpression: boolean, isGroup: boolean): stringMethodBuilds the canonical lookup key used to group compatible expression terms.
This is an internal canonicalization key, not a user-facing serialization format.
Numeric nodes normally collapse to Expression.numberHash; variables,
functions, exponentials, and infinities use multiplier-free identifiers; aggregate
nodes derive a key from their canonical elements. Group (GRP) handling can use the
power directly when isGroup is requested.
The exact key format is coupled to parser/algebra combination logic and should not
be persisted as an external interchange format.
Error Thrown when no key-generation rule exists for the node's internal type.
Parameters
| Name | Type | Description |
|---|---|---|
asSubExpression | boolean | Use the fuller sub-expression representation where supported. |
isGroup | boolean | Build a group-member key from this expression's power. |
Returns
string — The canonical lookup key.
latex(options?: TeXOptions): stringMethodLegacy alias for TeX conversion.
Parameters
| Name | Type | Description |
|---|---|---|
options | TeXOptions | — |
Returns
string
LOG: stringPropertyNames used by the internal logarithm representation and converters.
LOG10: stringPropertyNo description is available yet.
lt(x: string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational): booleanMethodTests whether this expression is < another value.
Nerdamer consults applicable assumptions and otherwise evaluates the difference
numerically/symbolically. These Expression comparison methods remain boolean for
compatibility. An unknown assumption result falls through to the ordinary comparison
path; if the relation still cannot be established, the method returns false. The
lower-level Assumption relations preserve unknown as undefined. Complex values are
not ordered and cause the comparison to throw.
core!UnsupportedOperationError Thrown when either side is classified as complex.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational | Value to compare with this expression. |
Returns
boolean — true when the requested ordering is established, otherwise false.
lte(x: string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational): booleanMethodTests whether this expression is <= another value.
Nerdamer consults applicable assumptions and otherwise evaluates the difference
numerically/symbolically. These Expression comparison methods remain boolean for
compatibility. An unknown assumption result falls through to the ordinary comparison
path; if the relation still cannot be established, the method returns false. The
lower-level Assumption relations preserve unknown as undefined. Complex values are
not ordered and cause the comparison to throw.
core!UnsupportedOperationError Thrown when either side is classified as complex.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | number | bigint | Decimal | Collection | Expression | Vector | ValuesSet | Matrix | Equation | Dictionary | Rational | Value to compare with this expression. |
Returns
boolean — true when the requested ordering is established, otherwise false.
minus(x: ExpressionInput): ExpressionMethodSubtracts x from this Expression.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The value to subtract. |
Returns
Expression — A new Expression representing this − x.
Examples
Expression.create('x').minus(1).text() // "-1+x"
Expression.create(10).minus(3).text() // "7"mod(x: ExpressionInput): ExpressionMethodComputes the modulo of this Expression by x.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The divisor. |
Returns
Expression — A new Expression representing this mod x.
Examples
Expression.create(10).mod(3).text() // "1"multiplier: RationalPropertyOuter rational coefficient carried by this node when explicitly initialized. Use Expression.getMultiplier to obtain the effective multiplier.
multiply(x: ExpressionInput): ExpressionMethodLegacy alias for times.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The value to multiply by. |
Returns
Expression — A new Expression representing this * x.
N(): ExpressionMethodCreates the internal summation/product index placeholder variable _n.
Returns
Expression — An Expression representing the variable _n.
name: stringPropertyThe function name if any
neg(): ExpressionMethodNegates this Expression by flipping the sign of the multiplier.
Returns
Expression — A new Expression equal to this * −1.
Examples
Expression.create(5).neg().text() // "-5"
Expression.create('x').neg().text() // "-x"NegInf(): ExpressionMethodCreates a symbolic negative infinity Expression.
Returns
Expression — An Expression representing −∞.
Examples
Expression.NegInf().text() // "-Infinity"Number(x: string | number | bigint | Decimal): ExpressionMethodCreates a numeric (NUM) expression node from a numeric representation.
This is a low-level constructor for numeric expression nodes. The supplied value is stored as text and is interpreted as a Rational when the multiplier is first requested. Use Expression.create when the input should be parsed as a general mathematical expression.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | number | bigint | Decimal | Numeric representation to store. |
Returns
Expression — A new numeric expression.
Examples
Expression.Number('42').text(); // "42"
Expression.Number('3/4').text(); // "3/4"numberHash: stringPropertyPlaceholder key used when numeric terms are grouped inside expression containers. This is part of the internal canonical-key representation rather than the rendered mathematical value of a number.
numerator(): ExpressionMethodLegacy alias for getNumerator.
Returns
Expression — The numerator Expression.
numeric(precision?: ExpressionInput): ExpressionMethodNo description is available yet.
Parameters
| Name | Type | Description |
|---|---|---|
precision | ExpressionInput | — |
Returns
parseValue(): ExpressionMethodCompatibility alias for the copy-oriented base extraction used by Expression.toLinearAndUnitMultiplier.
Returns
Expression — An independent Expression representing the node's mathematical base.
Pi(asNumericValue?: boolean): ExpressionMethodCreates π as a symbolic or evaluated expression.
Parameters
| Name | Type | Description |
|---|---|---|
asNumericValue | boolean | Force the evaluated representation even when parser evaluation mode is disabled. |
Returns
Expression — Symbolic pi, or its current numeric representation when evaluation is enabled.
Examples
Expression.Pi().text(); // "pi"
Expression.Pi(true).text(); // numeric approximationplus(x: ExpressionInput): ExpressionMethodAdds x to this Expression.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The value to add. |
Returns
Expression — A new Expression representing this + x.
Examples
Expression.create('x').plus(1).text() // "1+x"
Expression.create(2).plus(3).text() // "5"pow(x: ExpressionInput): ExpressionMethodRaises this expression to a symbolic or numeric exponent.
The operation delegates to Nerdamer's power canonicalization and simplification rules. Noninteger and complex powers follow principal-branch semantics; identities such as distributing a fractional power over arbitrary products are therefore applied only when the implementation can preserve the relevant branch. The receiver is not modified.
core!UndefinedError Thrown for undefined infinity-related powers handled by the power operation.
core!ZeroToZeroPowerError Thrown for zero-power cases classified as undefined by the power operation.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | Exponent to apply. |
Returns
Expression — The simplified power expression.
POW_OPR: stringPropertyPower operator used by expression text formatting.
power: ExpressionPropertyOuter power carried by this node when explicitly initialized. Use Expression.getPower to obtain the effective power.
precision: numberPropertyIf set, this is the maximum known precision of any of the intermediate operations
realPart(): ExpressionMethodReturns Nerdamer's symbolic decomposition of the real component.
Decomposition follows principal-branch handling for powered complex values.
Explicitly complex function calls that cannot be decomposed are preserved through
a symbolic realpart(...) wrapper rather than being guessed. The component
functions realpart(...) and imagpart(...) are themselves treated as real-valued.
Returns
Expression — The symbolic real component.
RESERVED: string[]PropertySymbols excluded from ordinary variable collection.
This list differs from the parser's restricted-name list.
It is used by expression traversal when deciding which VAR nodes should be
reported as free variables. The distinction is historical and should not be
interpreted as a general parser-reservation policy.
scientific: numberPropertySignificant digits requested by the legacy scientific-formatting helper.
setPower(x: Expression, power: Expression): ExpressionMethodSets the power of an Expression. Use this instead of assigning power directly.
Parameters
| Name | Type | Description |
|---|---|---|
x | Expression | The Expression whose power to set. |
power | Expression | The new power Expression. |
Returns
Expression — The modified Expression x.
sign(): numberMethodReturns the sign encoded by this node's coefficient representation.
This is not a general symbolic sign analysis. Most node types return the sign of
their outer Rational multiplier. EXP nodes additionally multiply that
result by the representation-level sign of their stored base. Unknown assumptions
are not inferred here.
Returns
number — -1, 0, or 1 from the represented coefficient/base sign.
signFree(): ExpressionMethodRemoves the sign represented by this expression's current form.
Complex expressions return their modulus sqrt(re^2 + im^2). For other
expressions, the method copies the node and removes a negative stored sign or
multiplier. This is representation-oriented normalization, not a general
assumption-driven implementation of symbolic abs(...).
Returns
Expression — A new sign-free expression or complex modulus.
simplify(): ExpressionMethodNo description is available yet.
Returns
solveFor(variable: ExpressionInput): SolutionSetMethodSolves the equation formed by setting this expression equal to zero.
Parameters
| Name | Type | Description |
|---|---|---|
variable | ExpressionInput | Variable to solve for. |
Returns
SolutionSet — The solver's SolutionSet, including any exclusions or root metadata it preserves.
sortFunction: ElementsSortTypePropertyComparator used when expression elements are emitted in canonical display order.
The ordering is representational, not a mathematical ordering relation. It keeps the imaginary unit last, orders like node types by value and descending power, and otherwise falls back to the internal expression-type order. Replacing this function changes ordering globally for subsequent formatting and reconstruction.
sptext(options?: TextOptions, asId?: boolean): stringMethodFormats this expression using SymPy-style ** exponentiation syntax.
Formatting temporarily switches the class-wide power-operator token while
delegating to the normal expression formatter, then restores ^. The expression
itself is not modified.
Parameters
| Name | Type | Description |
|---|---|---|
options | TextOptions | Formatting options accepted by the normal text formatter. |
asId | boolean | Request the internal identifier-oriented formatting mode. |
Returns
string — SymPy-compatible expression text.
sq(): ExpressionMethodSquares this Expression.
Returns
Expression — A new Expression representing this².
Examples
Expression.create('x').sq().text() // "x^2"
Expression.create(5).sq().text() // "25"strictEqual(x: ExpressionInput): booleanMethodTests Nerdamer equality while also requiring the same top-level internal type.
This is stricter than Expression.eq, but it is still not object identity or byte-for-byte tree equality. After verifying matching top-level types (or matching function names for function nodes), it delegates to Nerdamer's symbolic equality comparison.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | Value to compare with this expression. |
Returns
boolean — true when the type/name requirement and symbolic equality both hold.
sub(value: ExpressionInput, withValue: ExpressionInput): ExpressionMethodLegacy alias for subst.
Parameters
| Name | Type | Description |
|---|---|---|
value | ExpressionInput | The sub-expression to find. |
withValue | ExpressionInput | The replacement expression. |
Returns
Expression — A new Expression with the substitution applied.
subst(value: ExpressionInput, withValue: ExpressionInput): ExpressionMethodReplaces occurrences of one symbolic expression with another.
Substitution supports more than direct variable replacement: the underlying algorithm can match compatible products and sums, recurse into function arguments, and substitute within powers. Inputs are converted through Expression.create. The receiver is not mutated as part of normal execution. Unchanged branches can preserve the receiver's identity, and an exact match can return the supplied replacement object directly, so callers that require independent ownership should copy the result explicitly.
Parameters
| Name | Type | Description |
|---|---|---|
value | ExpressionInput | Symbolic value or sub-expression to match. |
withValue | ExpressionInput | Replacement value. |
Returns
Expression — The expression produced by the substitution algorithm.
subtract(x: ExpressionInput): ExpressionMethodLegacy alias for minus.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The value to subtract. |
Returns
Expression — A new Expression representing this − x.
symbols(...values: ExpressionInput[]): Expression[]MethodCreates multiple Expressions at once from a list of inputs.
Parameters
| Name | Type | Description |
|---|---|---|
values | ExpressionInput[] | One or more inputs to convert to Expressions. |
Returns
Expression[] — An array of Expressions.
Examples
const [x, y] = Expression.symbols('x', 'y');
x.text() // "x"
y.text() // "y"text(options?: TextOptions, asId?: boolean): stringMethodFormats this expression using Nerdamer's canonical text formatter.
Exact rational text is the default. Use sort: true to render terms in Nerdamer's
conventional display order without changing the stored expression. Decimal output,
precision, scientific notation, and power wrapping can also be selected per call. The asId mode is used
by internal identity/canonicalization logic and should not be
treated as a stable interchange format.
Parameters
| Name | Type | Description |
|---|---|---|
options | TextOptions | Text-formatting options. |
asId | boolean | Use the internal identifier-oriented formatting mode. |
Returns
string — The formatted expression text.
Examples
Expression.create('x^2 + 2*x + 1').text(); // "1+2*x+x^2"
Expression.create('x^2 + 2*x + 1').text({ sort: true }); // "x^2+2*x+1"
Expression.create('1/3').text(); // "1/3"
Expression.create('1/3').text({ decimal: true }); // decimal representation
Expression.create('12345').text({ scientific: 3 }); // "1.23e4"times(x: ExpressionInput): ExpressionMethodMultiplies this Expression by x.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | The value to multiply by. |
Returns
Expression — A new Expression representing this * x.
Examples
Expression.create('x').times(3).text() // "3*x"
Expression.create('x').times('y').text() // "x*y"toAccessor(target: Expression, indices: Expression[]): ExpressionMethodCreates the internal scalar Expression used to represent symbolic bracket access. The formatter renders this as ordinary bracket notation rather than exposing the internal function name.
Parameters
| Name | Type | Description |
|---|---|---|
target | Expression | — |
indices | Expression[] | — |
Returns
toDecimal(precision?: number): stringMethodFormats this expression using decimal numeric output.
This is a formatting operation equivalent to calling Expression.text with
{ decimal: true }; it does not convert the expression tree into a floating-point
data structure.
Parameters
| Name | Type | Description |
|---|---|---|
precision | number | Optional decimal formatting precision. |
Returns
string — Decimal-form expression text.
toEXP(x: ExpressionInput, pow: ExpressionInput, powerLess: boolean): ExpressionMethodConstructs an EXP node without applying the normal power simplification rules.
This is an internal representation helper for bases whose exponent must be stored
separately. When powerLess is true, the existing outer power is deleted from
the converted base before it is wrapped. Because Expression.create may
reuse an input Expression, callers must not use that option when the original
object must remain unchanged.
Parameters
| Name | Type | Description |
|---|---|---|
x | ExpressionInput | Base to store in the EXP node. |
pow | ExpressionInput | Exponent to store on the node. |
powerLess | boolean | Remove an existing outer power from the base before wrapping it. |
Returns
Expression — The constructed power expression, or the base itself when the base is one.
toFunction(name: string, args: NerdamerInput | undefined[]): ExpressionMethodConstructs a function node and assigns its arguments.
undefined entries are omitted. Existing Expression arguments may be retained
by identity because conversion uses Expression.create without requesting
copies. A Vector or Matrix carrying symbolic bracket access is first normalized
to its scalar accessor Expression; ordinary structured values remain invalid
function arguments where an Expression is required.
Parameters
| Name | Type | Description |
|---|---|---|
name | string | Function name stored on the node. |
args | NerdamerInput | undefined[] | Function arguments; undefined entries are ignored. |
Returns
Expression — The reconstructed function expression.
toLinearAndUnitMultiplier(): ExpressionMethodReturns an independent base expression with the outer multiplier and power removed.
Base extraction is defined by Expression.getBase. Because getBase()
exposes an EXP node's stored base by reference, this method copies
that base before returning it. Non-EXP bases are already independent copies.
Returns
Expression — An independent expression representing the node without its outer multiplier and power.
toString(options?: TextOptions): stringMethodReturns the string representation. Alias for text.
Parameters
| Name | Type | Description |
|---|---|---|
options | TextOptions | Formatting options passed to text. |
Returns
string — The text representation.
totalPower(): ExpressionMethodReturns the total degree of a monomial by summing the powers of all factors in a product expression. For non-product types, returns the expression's own power.
Returns
Expression — The total power as an Expression.
Examples
Expression.create('x^2*y^3').totalPower().text() // "5"
Expression.create('x^4').totalPower().text() // "4"toTeX(options?: TeXOptions): stringMethodConverts this expression to TeX using Nerdamer's converter.
Parameters
| Name | Type | Description |
|---|---|---|
options | TeXOptions | — |
Returns
string
toText(): stringMethodConverts this expression through Nerdamer's text converter.
Returns
string
toUnitMultiplier(): ExpressionMethodReturns a copy of this Expression with the multiplier removed (set to 1).
For NUM types (where the multiplier *is* the value), returns 1.
Returns
Expression — A new multiplier-free Expression.
Examples
Expression.create('3*x').toUnitMultiplier().text() // "x"
Expression.create(5).toUnitMultiplier().text() // "1"type: numberPropertyThe default type is a number for the expression since the default value for an expression is "1". The assert flag is used because TypeScript currently doesn't recognized that it's also set in the copyOver method
Type(x: string, type: number): ExpressionMethodLow-level helper that creates an Expression with a specific internal type.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | The value string. |
type | number | The Expression type constant (NUM, VAR, FUN, EXP, etc.). |
Returns
Expression — A new Expression of the specified type.
TYPES: { … }PropertyInternal expression-type constants used by parser and algebra code.
updateValue(aggregateElements?: Expression[]): ExpressionMethodRegenerates the stored value string from mutable structural state where supported.
Function nodes rebuild value from their name and arguments. Product and sum-like
nodes rebuild it from their current elements. Other node types are left unchanged.
This method mutates the receiver and returns the same object for chaining.
Parameters
| Name | Type | Description |
|---|---|---|
aggregateElements | Expression[] | Exact aggregate elements already available to a caller rebuilding a SUM/PRD node. When supplied, the generated value is also the ordinary lookup key and can seed the key cache without a second formatting pass. |
Returns
Expression — This expression after updating its stored value where applicable.
value: stringPropertyThe value of the expression. This hash is used for comparing variable. This value is set in the constructor or the copyOver method
valueOf(): string | numberMethodProvides the primitive value used by JavaScript coercion.
Numeric (NUM) expressions return the primitive value of their rational
multiplier. Other expressions return decimal-formatted text. This coercion API is
intended for JavaScript interoperability; use explicit symbolic comparison methods
when mathematical equality or ordering is required.
Returns
string | number — A number for numeric nodes, otherwise decimal-form expression text.
Variable(x: string): ExpressionMethodCreates a symbolic variable Expression.
Parameters
| Name | Type | Description |
|---|---|---|
x | string | The variable name. |
Returns
Expression — A VAR-typed Expression.
Examples
Expression.Variable('x').text() // "x"variables(vars?: string[]): string[]MethodCollects distinct free-variable names from this expression tree.
Only VAR nodes are collected. The current imaginary-unit symbol and names in
Expression.RESERVED are excluded. Traversal includes function arguments,
aggregate elements, and EXP bases and powers. Encounter order is preserved unless
the caller sorts the returned array separately.
If vars is supplied, new names are appended to that same accumulator without
duplicating names already present.
Parameters
| Name | Type | Description |
|---|---|---|
vars | string[] | Optional accumulator of names already collected. |
Returns
string[] — The accumulator containing distinct variable names.
