nerdamer 1.1.13 → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (387) hide show
  1. package/BREAKING_CHANGES.md +244 -5
  2. package/LICENSE.md +184 -0
  3. package/README.md +232 -318
  4. package/dist/bundle.js +2 -0
  5. package/dist/bundle.js.LICENSE.txt +7 -0
  6. package/dist/parser.js +2 -0
  7. package/dist/parser.js.LICENSE.txt +7 -0
  8. package/docs-data/parser-functions.json +2248 -0
  9. package/index.d.ts +10 -426
  10. package/output/algebra/adapters.d.ts +3 -0
  11. package/output/algebra/adapters.js +11 -0
  12. package/output/algebra/algorithms/arith.d.ts +84 -0
  13. package/output/algebra/algorithms/arith.js +324 -0
  14. package/output/algebra/algorithms/groebnerBase.d.ts +161 -0
  15. package/output/algebra/algorithms/groebnerBase.js +929 -0
  16. package/output/algebra/dispatch.d.ts +1 -0
  17. package/output/algebra/dispatch.js +25 -0
  18. package/output/algebra/factor/factor.d.ts +77 -0
  19. package/output/algebra/factor/factor.js +245 -0
  20. package/output/algebra/gcd/gcd.d.ts +30 -0
  21. package/output/algebra/gcd/gcd.js +95 -0
  22. package/output/algebra/groebner.d.ts +21 -0
  23. package/output/algebra/groebner.js +36 -0
  24. package/output/algebra/partfrac.d.ts +19 -0
  25. package/output/algebra/partfrac.js +365 -0
  26. package/output/algebra/polynomial/ModularSparsePolynomial.d.ts +131 -0
  27. package/output/algebra/polynomial/ModularSparsePolynomial.js +378 -0
  28. package/output/algebra/polynomial/ModularSparsePolynomialFactor.d.ts +40 -0
  29. package/output/algebra/polynomial/ModularSparsePolynomialFactor.js +661 -0
  30. package/output/algebra/polynomial/SparsePolynomialFactor.d.ts +64 -0
  31. package/output/algebra/polynomial/SparsePolynomialFactor.js +492 -0
  32. package/output/algebra/polynomial/SparsePolynomialGcd.d.ts +29 -0
  33. package/output/algebra/polynomial/SparsePolynomialGcd.js +259 -0
  34. package/output/algebra/polynomial/SparsePolynomialMultivariateFactor.d.ts +82 -0
  35. package/output/algebra/polynomial/SparsePolynomialMultivariateFactor.js +604 -0
  36. package/output/algebra/polynomial/modularGcd.d.ts +40 -0
  37. package/output/algebra/polynomial/modularGcd.js +365 -0
  38. package/output/algebra/polynomialize.d.ts +20 -0
  39. package/output/algebra/polynomialize.js +26 -0
  40. package/output/algebra/simplify/complexsimp.d.ts +7 -0
  41. package/output/algebra/simplify/complexsimp.js +24 -0
  42. package/output/algebra/simplify/factorCommon.d.ts +13 -0
  43. package/output/algebra/simplify/factorCommon.js +136 -0
  44. package/output/algebra/simplify/funcsimp.d.ts +26 -0
  45. package/output/algebra/simplify/funcsimp.js +633 -0
  46. package/output/algebra/simplify/invtrigrewrite.d.ts +10 -0
  47. package/output/algebra/simplify/invtrigrewrite.js +96 -0
  48. package/output/algebra/simplify/ratsimp.d.ts +21 -0
  49. package/output/algebra/simplify/ratsimp.js +140 -0
  50. package/output/algebra/simplify/simplify.d.ts +25 -0
  51. package/output/algebra/simplify/simplify.js +237 -0
  52. package/output/algebra/simplify/trigreduce.d.ts +38 -0
  53. package/output/algebra/simplify/trigreduce.js +424 -0
  54. package/output/algebra/simplify/trigrewrite.d.ts +17 -0
  55. package/output/algebra/simplify/trigrewrite.js +156 -0
  56. package/output/algebra/simplify/trigsimp.d.ts +11 -0
  57. package/output/algebra/simplify/trigsimp.js +369 -0
  58. package/output/algebra/simplify/utils.d.ts +32 -0
  59. package/output/algebra/simplify/utils.js +56 -0
  60. package/output/algebra/utils.d.ts +32 -0
  61. package/output/algebra/utils.js +48 -0
  62. package/output/api/advanced.d.ts +8 -0
  63. package/output/api/advanced.js +18 -0
  64. package/output/api/algebra.d.ts +17 -0
  65. package/output/api/algebra.js +35 -0
  66. package/output/api/assumptions.d.ts +4 -0
  67. package/output/api/assumptions.js +11 -0
  68. package/output/api/calculus.d.ts +10 -0
  69. package/output/api/calculus.js +22 -0
  70. package/output/api/core.d.ts +17 -0
  71. package/output/api/core.js +41 -0
  72. package/output/api/debug.d.ts +16 -0
  73. package/output/api/debug.js +23 -0
  74. package/output/api/languages/deu.d.ts +3 -0
  75. package/output/api/languages/deu.js +266 -0
  76. package/output/api/languages/fra.d.ts +3 -0
  77. package/output/api/languages/fra.js +266 -0
  78. package/output/api/languages/ita.d.ts +3 -0
  79. package/output/api/languages/ita.js +266 -0
  80. package/output/api/languages/nld.d.ts +3 -0
  81. package/output/api/languages/nld.js +266 -0
  82. package/output/api/languages/por.d.ts +3 -0
  83. package/output/api/languages/por.js +266 -0
  84. package/output/api/languages/spa.d.ts +3 -0
  85. package/output/api/languages/spa.js +266 -0
  86. package/output/api/parser.d.ts +93 -0
  87. package/output/api/parser.js +18 -0
  88. package/output/api/solve.d.ts +10 -0
  89. package/output/api/solve.js +17 -0
  90. package/output/api/structures.d.ts +10 -0
  91. package/output/api/structures.js +23 -0
  92. package/output/calculus/adapters.d.ts +8 -0
  93. package/output/calculus/adapters.js +41 -0
  94. package/output/calculus/derivative/diff.d.ts +30 -0
  95. package/output/calculus/derivative/diff.js +241 -0
  96. package/output/calculus/dispatch.d.ts +1 -0
  97. package/output/calculus/dispatch.js +25 -0
  98. package/output/calculus/fresnel.d.ts +16 -0
  99. package/output/calculus/fresnel.js +39 -0
  100. package/output/calculus/integrate/byParts.d.ts +18 -0
  101. package/output/calculus/integrate/byParts.js +339 -0
  102. package/output/calculus/integrate/bySubstitution.d.ts +135 -0
  103. package/output/calculus/integrate/bySubstitution.js +411 -0
  104. package/output/calculus/integrate/integrate.d.ts +38 -0
  105. package/output/calculus/integrate/integrate.js +652 -0
  106. package/output/calculus/integrate/integrationTable.d.ts +2 -0
  107. package/output/calculus/integrate/integrationTable.js +914 -0
  108. package/output/calculus/integrate/utils.d.ts +28 -0
  109. package/output/calculus/integrate/utils.js +96 -0
  110. package/output/calculus/laplace/ilaplace.d.ts +31 -0
  111. package/output/calculus/laplace/ilaplace.js +192 -0
  112. package/output/calculus/laplace/ilaplaceTable.d.ts +2 -0
  113. package/output/calculus/laplace/ilaplaceTable.js +200 -0
  114. package/output/calculus/laplace/laplace.d.ts +22 -0
  115. package/output/calculus/laplace/laplace.js +109 -0
  116. package/output/calculus/laplace/laplaceTable.d.ts +2 -0
  117. package/output/calculus/laplace/laplaceTable.js +187 -0
  118. package/output/calculus/limit/limit.d.ts +35 -0
  119. package/output/calculus/limit/limit.js +1183 -0
  120. package/output/calculus/limit/limitsTable.d.ts +2 -0
  121. package/output/calculus/limit/limitsTable.js +7 -0
  122. package/output/core/Settings.d.ts +32 -0
  123. package/output/core/Settings.js +68 -0
  124. package/output/core/classes/assumption/Assumption.d.ts +218 -0
  125. package/output/core/classes/assumption/Assumption.js +609 -0
  126. package/output/core/classes/assumption/assertiveFunctions.d.ts +6 -0
  127. package/output/core/classes/assumption/assertiveFunctions.js +64 -0
  128. package/output/core/classes/assumption/assume.d.ts +90 -0
  129. package/output/core/classes/assumption/assume.js +145 -0
  130. package/output/core/classes/assumption/dispatch.d.ts +1 -0
  131. package/output/core/classes/assumption/dispatch.js +11 -0
  132. package/output/core/classes/collection/Collection.d.ts +107 -0
  133. package/output/core/classes/collection/Collection.js +240 -0
  134. package/output/core/classes/complex/Complex.d.ts +109 -0
  135. package/output/core/classes/complex/Complex.js +153 -0
  136. package/output/core/classes/decimalSet/DecimalSet.d.ts +226 -0
  137. package/output/core/classes/decimalSet/DecimalSet.js +454 -0
  138. package/output/core/classes/dictionary/Dictionary.d.ts +102 -0
  139. package/output/core/classes/dictionary/Dictionary.js +216 -0
  140. package/output/core/classes/equation/Equation.d.ts +256 -0
  141. package/output/core/classes/equation/Equation.js +350 -0
  142. package/output/core/classes/expression/CoeffObject.d.ts +100 -0
  143. package/output/core/classes/expression/CoeffObject.js +197 -0
  144. package/output/core/classes/expression/Expression.d.ts +1691 -0
  145. package/output/core/classes/expression/Expression.js +2381 -0
  146. package/output/core/classes/expression/analysis.d.ts +25 -0
  147. package/output/core/classes/expression/analysis.js +218 -0
  148. package/output/core/classes/expression/collect.d.ts +9 -0
  149. package/output/core/classes/expression/collect.js +49 -0
  150. package/output/core/classes/expression/format.d.ts +54 -0
  151. package/output/core/classes/expression/format.js +340 -0
  152. package/output/core/classes/expression/products.d.ts +23 -0
  153. package/output/core/classes/expression/products.js +115 -0
  154. package/output/core/classes/expression/shortcuts.d.ts +35 -0
  155. package/output/core/classes/expression/shortcuts.js +129 -0
  156. package/output/core/classes/expression/traversal.d.ts +31 -0
  157. package/output/core/classes/expression/traversal.js +216 -0
  158. package/output/core/classes/expression/trig.d.ts +25 -0
  159. package/output/core/classes/expression/trig.js +40 -0
  160. package/output/core/classes/expression/utils.d.ts +61 -0
  161. package/output/core/classes/expression/utils.js +235 -0
  162. package/output/core/classes/lookupTable/LookupTable.d.ts +12 -0
  163. package/output/core/classes/lookupTable/LookupTable.js +55 -0
  164. package/output/core/classes/matrix/Matrix.d.ts +227 -0
  165. package/output/core/classes/matrix/Matrix.js +901 -0
  166. package/output/core/classes/matrix/Sylvester.d.ts +11 -0
  167. package/output/core/classes/matrix/Sylvester.js +54 -0
  168. package/output/core/classes/matrix/dispatch.d.ts +1 -0
  169. package/output/core/classes/matrix/dispatch.js +19 -0
  170. package/output/core/classes/matrix/functions.d.ts +28 -0
  171. package/output/core/classes/matrix/functions.js +57 -0
  172. package/output/core/classes/matrix/utils.d.ts +9 -0
  173. package/output/core/classes/matrix/utils.js +22 -0
  174. package/output/core/classes/parser/Parser.d.ts +493 -0
  175. package/output/core/classes/parser/Parser.js +1863 -0
  176. package/output/core/classes/parser/Token.d.ts +58 -0
  177. package/output/core/classes/parser/Token.js +137 -0
  178. package/output/core/classes/parser/constants.d.ts +162 -0
  179. package/output/core/classes/parser/constants.js +229 -0
  180. package/output/core/classes/parser/controlFlowSignals.d.ts +38 -0
  181. package/output/core/classes/parser/controlFlowSignals.js +60 -0
  182. package/output/core/classes/parser/helpers.d.ts +21 -0
  183. package/output/core/classes/parser/helpers.js +42 -0
  184. package/output/core/classes/parser/operations/add.d.ts +15 -0
  185. package/output/core/classes/parser/operations/add.js +236 -0
  186. package/output/core/classes/parser/operations/comma.d.ts +7 -0
  187. package/output/core/classes/parser/operations/comma.js +11 -0
  188. package/output/core/classes/parser/operations/compare.d.ts +21 -0
  189. package/output/core/classes/parser/operations/compare.js +474 -0
  190. package/output/core/classes/parser/operations/divide.d.ts +2 -0
  191. package/output/core/classes/parser/operations/divide.js +72 -0
  192. package/output/core/classes/parser/operations/functions.d.ts +46 -0
  193. package/output/core/classes/parser/operations/functions.js +438 -0
  194. package/output/core/classes/parser/operations/multiply.d.ts +11 -0
  195. package/output/core/classes/parser/operations/multiply.js +328 -0
  196. package/output/core/classes/parser/operations/power.d.ts +48 -0
  197. package/output/core/classes/parser/operations/power.js +673 -0
  198. package/output/core/classes/parser/operations/subtract.d.ts +3 -0
  199. package/output/core/classes/parser/operations/subtract.js +36 -0
  200. package/output/core/classes/parser/preprocess.d.ts +7 -0
  201. package/output/core/classes/parser/preprocess.js +246 -0
  202. package/output/core/classes/parser/scripting/controlFlow.d.ts +23 -0
  203. package/output/core/classes/parser/scripting/controlFlow.js +279 -0
  204. package/output/core/classes/parser/scripting/deferred.d.ts +4 -0
  205. package/output/core/classes/parser/scripting/deferred.js +65 -0
  206. package/output/core/classes/parser/scripting/dispatch.d.ts +1 -0
  207. package/output/core/classes/parser/scripting/dispatch.js +62 -0
  208. package/output/core/classes/parser/scripting/evaluate.d.ts +23 -0
  209. package/output/core/classes/parser/scripting/evaluate.js +128 -0
  210. package/output/core/classes/parser/scripting/functions.d.ts +14 -0
  211. package/output/core/classes/parser/scripting/functions.js +59 -0
  212. package/output/core/classes/parser/scripting/scope.d.ts +8 -0
  213. package/output/core/classes/parser/scripting/scope.js +132 -0
  214. package/output/core/classes/parser/types.d.ts +130 -0
  215. package/output/core/classes/parser/types.js +2 -0
  216. package/output/core/classes/parser/wrappers/IndexedReference.d.ts +31 -0
  217. package/output/core/classes/parser/wrappers/IndexedReference.js +68 -0
  218. package/output/core/classes/parser/wrappers/KeyValuePair.d.ts +24 -0
  219. package/output/core/classes/parser/wrappers/KeyValuePair.js +51 -0
  220. package/output/core/classes/polynomial/Polynomial.d.ts +504 -0
  221. package/output/core/classes/polynomial/Polynomial.js +1195 -0
  222. package/output/core/classes/polynomial/SparsePolynomial.d.ts +221 -0
  223. package/output/core/classes/polynomial/SparsePolynomial.js +824 -0
  224. package/output/core/classes/polynomial/SparsePolynomialAdapter.d.ts +56 -0
  225. package/output/core/classes/polynomial/SparsePolynomialAdapter.js +241 -0
  226. package/output/core/classes/polynomial/Term.d.ts +222 -0
  227. package/output/core/classes/polynomial/Term.js +430 -0
  228. package/output/core/classes/polynomial/adapters.d.ts +18 -0
  229. package/output/core/classes/polynomial/adapters.js +33 -0
  230. package/output/core/classes/polynomial/dispatch.d.ts +1 -0
  231. package/output/core/classes/polynomial/dispatch.js +14 -0
  232. package/output/core/classes/polynomial/functions.d.ts +77 -0
  233. package/output/core/classes/polynomial/functions.js +189 -0
  234. package/output/core/classes/polynomial/utils.d.ts +62 -0
  235. package/output/core/classes/polynomial/utils.js +207 -0
  236. package/output/core/classes/rational/Rational.d.ts +501 -0
  237. package/output/core/classes/rational/Rational.js +829 -0
  238. package/output/core/classes/seq/SEQ.d.ts +13 -0
  239. package/output/core/classes/seq/SEQ.js +137 -0
  240. package/output/core/classes/valuesSet/ValuesSet.d.ts +187 -0
  241. package/output/core/classes/valuesSet/ValuesSet.js +399 -0
  242. package/output/core/classes/vector/Vector.d.ts +222 -0
  243. package/output/core/classes/vector/Vector.js +501 -0
  244. package/output/core/classes/vector/dispatch.d.ts +1 -0
  245. package/output/core/classes/vector/dispatch.js +11 -0
  246. package/output/core/classes/vector/functions.d.ts +28 -0
  247. package/output/core/classes/vector/functions.js +47 -0
  248. package/output/core/common/classes/MathematicalAggregate.d.ts +53 -0
  249. package/output/core/common/classes/MathematicalAggregate.js +149 -0
  250. package/output/core/common/classes/Scope.d.ts +62 -0
  251. package/output/core/common/classes/Scope.js +122 -0
  252. package/output/core/common/classes/StructuredEntity.d.ts +55 -0
  253. package/output/core/common/classes/StructuredEntity.js +151 -0
  254. package/output/core/common/common.d.ts +62 -0
  255. package/output/core/common/common.js +74 -0
  256. package/output/core/common/functions/functions.d.ts +14 -0
  257. package/output/core/common/functions/functions.js +33 -0
  258. package/output/core/common/functions/structuredEntityUtils.d.ts +27 -0
  259. package/output/core/common/functions/structuredEntityUtils.js +40 -0
  260. package/output/core/converters/BaseConverter.d.ts +97 -0
  261. package/output/core/converters/BaseConverter.js +405 -0
  262. package/output/core/converters/Converter.d.ts +111 -0
  263. package/output/core/converters/Converter.js +806 -0
  264. package/output/core/converters/Pattern.d.ts +71 -0
  265. package/output/core/converters/Pattern.js +302 -0
  266. package/output/core/dispatch.d.ts +52 -0
  267. package/output/core/dispatch.js +26 -0
  268. package/output/core/errors.d.ts +316 -0
  269. package/output/core/errors.js +349 -0
  270. package/output/core/fullFunctions.d.ts +7 -0
  271. package/output/core/fullFunctions.js +31 -0
  272. package/output/core/functions/bigint/bigint.d.ts +133 -0
  273. package/output/core/functions/bigint/bigint.js +444 -0
  274. package/output/core/functions/bigint/primeFactor.d.ts +51 -0
  275. package/output/core/functions/bigint/primeFactor.js +267 -0
  276. package/output/core/functions/bigint/primes.d.ts +1 -0
  277. package/output/core/functions/bigint/primes.js +11 -0
  278. package/output/core/functions/build/definitions.d.ts +12 -0
  279. package/output/core/functions/build/definitions.js +139 -0
  280. package/output/core/functions/build/index.d.ts +32 -0
  281. package/output/core/functions/build/index.js +136 -0
  282. package/output/core/functions/complex.d.ts +90 -0
  283. package/output/core/functions/complex.dispatch.d.ts +1 -0
  284. package/output/core/functions/complex.dispatch.js +16 -0
  285. package/output/core/functions/complex.js +482 -0
  286. package/output/core/functions/decimal.d.ts +24 -0
  287. package/output/core/functions/decimal.js +665 -0
  288. package/output/core/functions/expand/expand.d.ts +42 -0
  289. package/output/core/functions/expand/expand.js +376 -0
  290. package/output/core/functions/fresnelNumeric.d.ts +12 -0
  291. package/output/core/functions/fresnelNumeric.js +123 -0
  292. package/output/core/functions/numeric.d.ts +140 -0
  293. package/output/core/functions/numeric.js +790 -0
  294. package/output/core/functions/rationalNormalization.d.ts +11 -0
  295. package/output/core/functions/rationalNormalization.js +117 -0
  296. package/output/core/functions/setFunction.d.ts +19 -0
  297. package/output/core/functions/setFunction.js +75 -0
  298. package/output/core/functions/string.d.ts +26 -0
  299. package/output/core/functions/string.js +102 -0
  300. package/output/core/functions/subst.d.ts +90 -0
  301. package/output/core/functions/subst.js +506 -0
  302. package/output/core/functions/utils.d.ts +24 -0
  303. package/output/core/functions/utils.js +51 -0
  304. package/output/core/parserFunctions.d.ts +7 -0
  305. package/output/core/parserFunctions.js +25 -0
  306. package/output/core/types.d.ts +48 -0
  307. package/output/core/types.js +2 -0
  308. package/output/index.d.ts +359 -0
  309. package/output/index.js +739 -0
  310. package/output/math/defint/defint.d.ts +18 -0
  311. package/output/math/defint/defint.js +60 -0
  312. package/output/math/defint/defintDecimal.d.ts +37 -0
  313. package/output/math/defint/defintDecimal.js +321 -0
  314. package/output/math/defint/defintNative.d.ts +57 -0
  315. package/output/math/defint/defintNative.js +281 -0
  316. package/output/math/dispatch.d.ts +1 -0
  317. package/output/math/dispatch.js +101 -0
  318. package/output/math/geometry.d.ts +12 -0
  319. package/output/math/geometry.js +55 -0
  320. package/output/math/math.d.ts +695 -0
  321. package/output/math/math.js +1955 -0
  322. package/output/math/trig.d.ts +518 -0
  323. package/output/math/trig.js +1444 -0
  324. package/output/math/trunc.d.ts +19 -0
  325. package/output/math/trunc.js +36 -0
  326. package/output/math/utils.d.ts +66 -0
  327. package/output/math/utils.js +219 -0
  328. package/output/solve/classes/DecimalMatrix.d.ts +17 -0
  329. package/output/solve/classes/DecimalMatrix.js +86 -0
  330. package/output/solve/classes/FunctionSolver.d.ts +135 -0
  331. package/output/solve/classes/FunctionSolver.js +433 -0
  332. package/output/solve/classes/MultivariateSolver.d.ts +84 -0
  333. package/output/solve/classes/MultivariateSolver.js +240 -0
  334. package/output/solve/classes/PolynomialSolver.d.ts +104 -0
  335. package/output/solve/classes/PolynomialSolver.js +492 -0
  336. package/output/solve/classes/SolutionSet.d.ts +172 -0
  337. package/output/solve/classes/SolutionSet.js +434 -0
  338. package/output/solve/classes/Solver.d.ts +17 -0
  339. package/output/solve/classes/Solver.js +132 -0
  340. package/output/solve/classes/SymbolicSolver.d.ts +74 -0
  341. package/output/solve/classes/SymbolicSolver.js +601 -0
  342. package/output/solve/dispatch.d.ts +1 -0
  343. package/output/solve/dispatch.js +13 -0
  344. package/output/solve/linsolve.d.ts +53 -0
  345. package/output/solve/linsolve.js +233 -0
  346. package/output/solve/solve.d.ts +44 -0
  347. package/output/solve/solve.js +368 -0
  348. package/output/solve/solveSystem.d.ts +31 -0
  349. package/output/solve/solveSystem.js +266 -0
  350. package/output/solve/utils.d.ts +10 -0
  351. package/output/solve/utils.js +58 -0
  352. package/output/utils/array.d.ts +42 -0
  353. package/output/utils/array.js +98 -0
  354. package/output/utils/debug.d.ts +131 -0
  355. package/output/utils/debug.js +296 -0
  356. package/output/utils/decimal.d.ts +3 -0
  357. package/output/utils/decimal.js +16 -0
  358. package/output/utils/numeric.d.ts +14 -0
  359. package/output/utils/numeric.js +51 -0
  360. package/output/utils/object.d.ts +26 -0
  361. package/output/utils/object.js +56 -0
  362. package/package.json +178 -57
  363. package/.travis.yml +0 -3
  364. package/Algebra.js +0 -4568
  365. package/CODE_OF_CONDUCT.md +0 -46
  366. package/CONTRIBUTING.md +0 -14
  367. package/Calculus.js +0 -2675
  368. package/Extra.js +0 -622
  369. package/Solve.js +0 -1783
  370. package/all.js +0 -16
  371. package/all.min.js +0 -1
  372. package/gulpfile.js +0 -16
  373. package/index.html +0 -158
  374. package/license.txt +0 -19
  375. package/nerdamer.core.js +0 -12510
  376. package/spec/LaTeX.spec.js +0 -302
  377. package/spec/TeXConvert.spec.js +0 -8
  378. package/spec/algebra.spec.js +0 -287
  379. package/spec/basic_parser.spec.js +0 -134
  380. package/spec/build.spec.js +0 -131
  381. package/spec/calculus.spec.js +0 -183
  382. package/spec/core.spec.js +0 -2970
  383. package/spec/extra.spec.js +0 -54
  384. package/spec/solve.spec.js +0 -126
  385. package/spec/support/jasmine.json +0 -11
  386. package/spec/support/utils.js +0 -42
  387. package/spec/text.spec.js +0 -132
@@ -0,0 +1,2381 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Expression = void 0;
7
+ const decimal_js_1 = __importDefault(require("decimal.js"));
8
+ const math_1 = require("../../../math/math");
9
+ const common_1 = require("../../common/common");
10
+ const errors_1 = require("../../errors");
11
+ const build_1 = require("../../functions/build");
12
+ const complex_1 = require("../../functions/complex");
13
+ const expand_1 = require("../../functions/expand/expand");
14
+ const subst_1 = require("../../functions/subst");
15
+ const Settings_1 = require("../../Settings");
16
+ const constants_1 = require("../parser/constants");
17
+ const add_1 = require("../parser/operations/add");
18
+ const compare_1 = require("../parser/operations/compare");
19
+ const divide_1 = require("../parser/operations/divide");
20
+ // import { multiply, add, subtract, divide, power, equal, gt, gte } from '../parser';
21
+ const multiply_1 = require("../parser/operations/multiply");
22
+ const power_1 = require("../parser/operations/power");
23
+ const power_2 = require("../parser/operations/power");
24
+ const subtract_1 = require("../parser/operations/subtract");
25
+ const Parser_1 = require("../parser/Parser");
26
+ const Rational_1 = require("../rational/Rational");
27
+ const analysis_1 = require("./analysis");
28
+ const analysis_2 = require("./analysis");
29
+ const analysis_3 = require("./analysis");
30
+ const format_1 = require("./format");
31
+ const shortcuts_1 = require("./shortcuts");
32
+ const traversal_1 = require("./traversal");
33
+ const traversal_2 = require("./traversal");
34
+ const traversal_3 = require("./traversal");
35
+ const utils_1 = require("./utils");
36
+ const { NUM, VAR, EXP, FUN, GRP, PRD, SUM, INF } = constants_1.EXPRESSION_TYPES;
37
+ /**
38
+ * Represents a symbolic expression in Nerdamer's canonical expression tree.
39
+ *
40
+ * @remarks
41
+ * `Expression` is the central symbolic value type used by the parser and by the
42
+ * algebra, calculus, and solver layers. Parsed expressions are normalized into a
43
+ * small set of internal node categories such as numbers, variables, functions,
44
+ * powers, products, and sums. Numeric coefficients are normally stored in a
45
+ * {@link Rational} multiplier rather than as separate product elements.
46
+ *
47
+ * Most arithmetic and transformation methods return a new `Expression`, but the
48
+ * class itself is mutable because parser and algorithm internals rebuild nodes in
49
+ * place. Accessors such as {@link Expression.getArguments},
50
+ * {@link Expression.getMultiplier}, and {@link Expression.getPower} may lazily
51
+ * initialize and return internal objects. Use {@link Expression.copy} when an
52
+ * independently mutable expression tree is required.
53
+ *
54
+ * {@link Expression.create} is the preferred construction API for ordinary
55
+ * expression construction and coercion. It centralizes supported input handling and
56
+ * normalization. When the input is already an `Expression`, it preserves object
57
+ * identity unless its `copy` argument is set to `true`.
58
+ *
59
+ * When the source is already known to be an `Expression` and an independent tree is
60
+ * required, use {@link Expression.copy}. When a caller accepts broader input but must
61
+ * guarantee a clone for an existing expression, use
62
+ * `Expression.create(input, undefined, true)`.
63
+ *
64
+ * Direct `new Expression(...)` construction is reserved for representation-level
65
+ * internals that require constructor semantics, such as the `plainConstruct` path and
66
+ * the implementation of {@link Expression.copy}. Ordinary callers should not use the
67
+ * constructor for coercion or cloning.
68
+ *
69
+ * The internal expression groups are organizational categories used by Nerdamer's
70
+ * canonicalization logic. They should not be confused with general mathematical
71
+ * classifications:
72
+ *
73
+ * - `NUM` stores plain numeric values.
74
+ * - `VAR` stores symbols/variables whose powers fit the variable representation.
75
+ * - `EXP` stores bases with powers that require a separate exponential node; it is
76
+ * not the same thing as an exponential function.
77
+ * - `FUN` stores function calls.
78
+ * - `GRP` stores sums with a common base but differing powers, such as
79
+ * `x + x^y` or `cos(x) - 3*cos(x)^2`.
80
+ * - `PRD` stores products of non-numeric symbolic factors; numeric coefficients are
81
+ * moved to the outer multiplier during parsing.
82
+ * - `SUM` stores other sums. For example, `1 + x + x^2` is a `SUM` containing a
83
+ * numeric term and a grouped polynomial-like component.
84
+ * - `INF` stores infinite values.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const expression = Expression.create('2*x + 1');
89
+ *
90
+ * expression.text(); // "1+2*x"
91
+ * expression.evaluate({ x: 3 }).text(); // "7"
92
+ * ```
93
+ */
94
+ class Expression {
95
+ /**
96
+ * Controls whether addition first distributes an outer multiplier on a sum.
97
+ *
98
+ * @remarks
99
+ * This is a process-wide parser/algebra setting used by the addition operation.
100
+ * Changing it affects subsequent symbolic operations globally.
101
+ */
102
+ static DISTRIBUTE_MULTIPLIER = true;
103
+ /**
104
+ * The symbol currently reserved for the imaginary unit.
105
+ *
106
+ * Use {@link Parser.setI} to change the symbol so the parser's restricted-name
107
+ * bookkeeping is updated at the same time.
108
+ */
109
+ static imaginary = constants_1.DEFAULT_IMAGINARY;
110
+ /** Names used by the internal logarithm representation and converters. */
111
+ static LOG = constants_1.LOG;
112
+ static LOG10 = 'log_10';
113
+ /**
114
+ * Placeholder key used when numeric terms are grouped inside expression containers.
115
+ *
116
+ * This is part of the internal canonical-key representation rather than the
117
+ * rendered mathematical value of a number.
118
+ */
119
+ static numberHash = '#';
120
+ /** Power operator used by expression text formatting. */
121
+ static POW_OPR = '^';
122
+ /**
123
+ * Symbols excluded from ordinary variable collection.
124
+ *
125
+ * @remarks
126
+ * This list differs from the parser's restricted-name list.
127
+ * It is used by expression traversal when deciding which `VAR` nodes should be
128
+ * reported as free variables. The distinction is historical and should not be
129
+ * interpreted as a general parser-reservation policy.
130
+ */
131
+ static RESERVED = [constants_1.E].concat(constants_1.PI).concat(constants_1.INFINITY);
132
+ /**
133
+ * Comparator used when expression elements are emitted in canonical display order.
134
+ *
135
+ * @remarks
136
+ * The ordering is representational, not a mathematical ordering relation. It keeps
137
+ * the imaginary unit last, orders like node types by value and descending power,
138
+ * and otherwise falls back to the internal expression-type order. Replacing this
139
+ * function changes ordering globally for subsequent formatting and reconstruction.
140
+ */
141
+ static sortFunction = (a, b) => {
142
+ // Ensure that i is last e.g. 1 + i and not i + 1;
143
+ if (a.isI()) {
144
+ return 1;
145
+ }
146
+ // Ensure a,b,x,y,...
147
+ if (a.type === b.type) {
148
+ // Ensure that x^2 is before x
149
+ if (a.value === b.value) {
150
+ return Number(b.getPower()) - Number(a.getPower());
151
+ }
152
+ if (a.value > b.value) {
153
+ return 1;
154
+ }
155
+ if (b.value > a.value) {
156
+ return -1;
157
+ }
158
+ return 0;
159
+ }
160
+ // The remaining order is per types
161
+ // Default: Exponential > Variable > Functions > Sums/Polynomials > Multivariate Monomials > Infinity
162
+ return a.type - b.type;
163
+ };
164
+ /** Internal expression-type constants used by parser and algebra code. */
165
+ static TYPES = constants_1.EXPRESSION_TYPES;
166
+ /**
167
+ * Arguments stored by a function node.
168
+ *
169
+ * Prefer {@link Expression.getArguments} when consuming this representation.
170
+ */
171
+ args;
172
+ /**
173
+ * Explicit mathematical base stored by an `EXP` node.
174
+ *
175
+ * Non-`EXP` nodes derive their base through {@link Expression.getBase} instead.
176
+ */
177
+ base;
178
+ /** Parser entity discriminator for expression values. */
179
+ dataType = constants_1.EXPRESSION;
180
+ /**
181
+ * Signals that the Expression was parsed with the deferred flag true
182
+ */
183
+ deferred = false;
184
+ /**
185
+ * Canonically keyed child expressions for aggregate nodes such as sums and products.
186
+ *
187
+ * @remarks
188
+ * The record is mutable representation state. {@link Expression.getElements}
189
+ * returns this object directly when it exists; callers that mutate it are
190
+ * responsible for preserving a valid expression representation and regenerating derived values.
191
+ */
192
+ elements = undefined;
193
+ /**
194
+ * Cached ordinary lookup key for SUM and PRD nodes.
195
+ *
196
+ * Copies intentionally start without this cache. Aggregate reconstruction clears it
197
+ * through updateValue() before the node is used again.
198
+ */
199
+ _keyValueCache;
200
+ /**
201
+ * Let's the parser know not to treat it as a set of values
202
+ */
203
+ isEnumerable = false;
204
+ /**
205
+ * Outer rational coefficient carried by this node when explicitly initialized.
206
+ *
207
+ * Use {@link Expression.getMultiplier} to obtain the effective multiplier.
208
+ */
209
+ multiplier;
210
+ /**
211
+ * The function name if any
212
+ */
213
+ name;
214
+ /**
215
+ * Outer power carried by this node when explicitly initialized.
216
+ *
217
+ * Use {@link Expression.getPower} to obtain the effective power.
218
+ */
219
+ power;
220
+ /**
221
+ * If set, this is the maximum known precision of any of the intermediate operations
222
+ */
223
+ precision;
224
+ /** Significant digits requested by the legacy scientific-formatting helper. */
225
+ scientific;
226
+ /**
227
+ * The default type is a number for the expression since the default value
228
+ * for an expression is "1". The assert flag is used because TypeScript
229
+ * currently doesn't recognized that it's also set in the copyOver method
230
+ */
231
+ type;
232
+ /**
233
+ * The value of the expression. This hash is used for comparing variable.
234
+ * This value is set in the constructor or the copyOver method
235
+ */
236
+ value;
237
+ /**
238
+ * Constructs or copies an expression value.
239
+ *
240
+ * @remarks
241
+ * Direct construction is primarily a representation-level API. When `x` is an
242
+ * existing `Expression`, the constructor deep-copies its expression tree. When
243
+ * `plainConstruct` is `true` and `x` is a string, that string is stored as the
244
+ * raw node value without parsing. Other inputs are delegated to
245
+ * {@link Expression.create}, and JavaScript constructor return semantics therefore
246
+ * allow that factory-created expression to become the result of `new Expression(...)`.
247
+ *
248
+ * Ordinary code should use {@link Expression.create} for construction/coercion and
249
+ * {@link Expression.copy} when an independent tree is required. Direct constructor
250
+ * calls are reserved for low-level representation code.
251
+ *
252
+ * @param x - The expression or Nerdamer input used to construct the value.
253
+ * @param plainConstruct - Store a string as a raw internal value instead of parsing it.
254
+ */
255
+ constructor(x, plainConstruct) {
256
+ // Allow for hooking of the input. The user can override the hook to modify
257
+ // how the input is handled.
258
+ x = Expression.hook(x);
259
+ if (plainConstruct && typeof x === 'string') {
260
+ this.value = x;
261
+ return this;
262
+ }
263
+ else if (Expression.isExpression(x)) {
264
+ (0, utils_1.copyOver)(x, this);
265
+ }
266
+ else {
267
+ return Expression.create(x);
268
+ }
269
+ }
270
+ /**
271
+ * Converts supported Nerdamer input into an `Expression`.
272
+ *
273
+ * @remarks
274
+ * Strings and primitive numeric inputs are parsed through {@link Parser}. An
275
+ * existing `Expression` is returned unchanged when no substitution `values` are
276
+ * supplied; pass `copy: true` to request an independent deep copy. A
277
+ * {@link Rational} is converted to a numeric expression while preserving its
278
+ * decimal-origin marker.
279
+ *
280
+ * An {@link Equation} is converted to its residual expression by moving the right
281
+ * side to the left on a copy of the equation. For example, `x = 2` becomes the
282
+ * expression `x - 2` in canonical form.
283
+ *
284
+ * @param x - The expression-compatible input to convert.
285
+ * @param values - Parser substitutions applied while parsing non-`Expression` input.
286
+ * @param copy - Copy an existing `Expression` instead of preserving its identity.
287
+ * @returns The parsed, converted, reused, or copied expression.
288
+ * @throws {@link core!UnexpectedDataType}
289
+ * Thrown when parsing produces another parser entity, such as a vector or matrix,
290
+ * where an `Expression` is required.
291
+ *
292
+ * @example
293
+ * ```ts
294
+ * const expression = Expression.create('x^2 + 1');
295
+ *
296
+ * Expression.create(expression) === expression; // true
297
+ * Expression.create(expression, undefined, true) === expression; // false
298
+ * Expression.create('a+b', { a: 2, b: 3 }).text(); // "5"
299
+ * ```
300
+ */
301
+ static create(x, values, copy) {
302
+ if (Expression.isExpression(x) && !values) {
303
+ return copy ? x.copy() : x;
304
+ }
305
+ else if (Rational_1.Rational.isRational(x)) {
306
+ return Expression.fromRational(x);
307
+ }
308
+ else if ((0, common_1.isNerdamerNativeType)(x, constants_1.EQUATION)) {
309
+ return x.toLHS().LHS;
310
+ }
311
+ const retval = Parser_1.Parser.parse(String(x), values);
312
+ if (!Expression.isExpression(retval)) {
313
+ throw new errors_1.UnexpectedDataType((0, errors_1.message)('expressionExpected', { type: constants_1.dataTypes[retval.dataType] }));
314
+ }
315
+ return retval;
316
+ }
317
+ /**
318
+ * Creates Euler's constant as a symbolic or evaluated expression.
319
+ *
320
+ * @param asNumericValue - Force the evaluated representation even when parser
321
+ * evaluation mode is disabled.
322
+ * @returns Symbolic `e`, or its current numeric representation when evaluation is enabled.
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * Expression.E().text(); // "e"
327
+ * Expression.E(true).text(); // numeric approximation
328
+ * ```
329
+ */
330
+ static E(asNumericValue) {
331
+ if (Settings_1.Settings.EVALUATE || asNumericValue) {
332
+ return Expression.fromRational(Rational_1.Rational.E);
333
+ }
334
+ return Expression.Variable(constants_1.E);
335
+ }
336
+ /**
337
+ * Converts a rational value into a numeric expression.
338
+ *
339
+ * The conversion preserves the rational's `asDecimal` provenance flag so later
340
+ * formatting and decimal-contagion logic can distinguish decimal-origin values.
341
+ *
342
+ * @param x - Rational value to convert.
343
+ * @returns A new numeric expression with an independent multiplier.
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * const rational = Rational.create('3/4');
348
+ * Expression.fromRational(rational).text(); // "3/4"
349
+ * ```
350
+ */
351
+ static fromRational(x) {
352
+ const value = x.denominator === 1n ? x.numerator.toString() : `${x.numerator}/${x.denominator}`;
353
+ const retval = Expression.Number(value);
354
+ retval.getMultiplier().asDecimal = x.asDecimal;
355
+ return retval;
356
+ }
357
+ /**
358
+ * Converts a structured entity carrying symbolic bracket access into the scalar
359
+ * Expression form used by ordinary algebra and function nodes.
360
+ *
361
+ * Structured entities without symbolic access are left unchanged by returning
362
+ * `undefined`; callers can then apply their normal conversion rules.
363
+ */
364
+ static fromSymbolicAccess(x) {
365
+ let retval;
366
+ if (typeof x === 'object' && x !== null) {
367
+ const structured = x;
368
+ const target = structured.symbolicTarget;
369
+ const indices = structured.symbolicAccessor;
370
+ if (Expression.isExpression(target) &&
371
+ indices &&
372
+ indices.length > 0 &&
373
+ indices.every(index => Expression.isExpression(index))) {
374
+ retval = Expression.toAccessor(target, indices);
375
+ }
376
+ }
377
+ return retval;
378
+ }
379
+ /**
380
+ * Creates a symbolic function node with the given name.
381
+ *
382
+ * This creates a bare function symbol without arguments. To create a function
383
+ * with arguments, use {@link Expression.toFunction} instead.
384
+ *
385
+ * @param x - The function name.
386
+ * @returns A function-typed Expression.
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * Expression.Function('f').text() // "f"
391
+ * ```
392
+ */
393
+ static Function(x) {
394
+ const retval = Expression.Type(x, FUN);
395
+ retval.name = x;
396
+ return retval;
397
+ }
398
+ /**
399
+ * Generates a canonical string representation for an array of sub-expressions,
400
+ * joined by `+` (for SUM/GRP) or `*` (for PRD), with sums wrapped in parentheses
401
+ * when inside a product.
402
+ *
403
+ * @param arr - The array of sub-expressions.
404
+ * @param f - The string method to call on each element: `'idString'`, `'keyValue'`, or `'text'`.
405
+ * @param expressionType - The parent expression type (SUM, GRP, or PRD).
406
+ * @returns The joined string representation.
407
+ */
408
+ static getValue(arr, f, expressionType) {
409
+ return arr
410
+ .map(x => {
411
+ // This will call the toString or keyValue depending on what's requested
412
+ let retval = x[f]();
413
+ if ((x.type === SUM || x.type === GRP) && expressionType === PRD) {
414
+ //e.g. (x+1)*x; The x+1 should be wrapped in a brackets
415
+ retval = `(${retval})`;
416
+ }
417
+ return retval;
418
+ })
419
+ .sort()
420
+ .join(expressionType === SUM || expressionType === GRP ? '+' : '*')
421
+ .replace('+-', '-');
422
+ }
423
+ /**
424
+ * Intercepts values passed through the `Expression` constructor.
425
+ *
426
+ * @remarks
427
+ * The default implementation is the identity function. Applications may replace
428
+ * this static hook, but doing so changes direct-construction behavior globally.
429
+ * {@link Expression.create} does not route every parsed input through this hook.
430
+ *
431
+ * @param x - Raw constructor input.
432
+ * @returns The value the constructor should continue processing.
433
+ */
434
+ static hook(x) {
435
+ return x;
436
+ }
437
+ /**
438
+ * Creates the variable node representing the current imaginary-unit symbol.
439
+ *
440
+ * @returns A new variable expression using {@link Expression.imaginary}.
441
+ *
442
+ * @example
443
+ * ```ts
444
+ * Expression.Img().text(); // "i" with the default parser configuration
445
+ * ```
446
+ *
447
+ * @see {@link Parser.setI}
448
+ */
449
+ static Img() {
450
+ return Expression.Variable(Expression.imaginary);
451
+ }
452
+ /**
453
+ * Creates a symbolic positive infinity Expression.
454
+ *
455
+ * @returns An Expression representing `+∞`.
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * Expression.Inf().text() // "Infinity"
460
+ * ```
461
+ */
462
+ static Inf() {
463
+ return Expression.Type(constants_1.INFINITY[0], INF);
464
+ }
465
+ /**
466
+ * Type guard that checks whether an object is an Expression.
467
+ *
468
+ * @param obj - The value to test.
469
+ * @returns `true` if `obj` is an Expression instance.
470
+ *
471
+ * @example
472
+ * ```ts
473
+ * Expression.isExpression(Expression.create('x')) // true
474
+ * Expression.isExpression(42) // false
475
+ * ```
476
+ */
477
+ static isExpression(obj) {
478
+ return (0, common_1.isNerdamerNativeType)(obj, constants_1.EXPRESSION);
479
+ }
480
+ /**
481
+ * Type guard that checks whether every element of an array is an Expression.
482
+ *
483
+ * @param obj - The value to test.
484
+ * @returns `true` if `obj` is an array and all elements are Expressions.
485
+ */
486
+ static isExpressionArray(obj) {
487
+ if (!Array.isArray(obj)) {
488
+ return false;
489
+ }
490
+ for (let i = 0; i < obj.length; i++) {
491
+ if (!Expression.isExpression(obj[i])) {
492
+ return false;
493
+ }
494
+ }
495
+ return true;
496
+ }
497
+ /**
498
+ * Creates the internal summation/product index placeholder variable `_n`.
499
+ *
500
+ * @returns An Expression representing the variable `_n`.
501
+ */
502
+ static N() {
503
+ return Expression.Variable(constants_1.INDEX_VARIABLE);
504
+ }
505
+ /**
506
+ * Creates a symbolic negative infinity Expression.
507
+ *
508
+ * @returns An Expression representing `−∞`.
509
+ *
510
+ * @example
511
+ * ```ts
512
+ * Expression.NegInf().text() // "-Infinity"
513
+ * ```
514
+ */
515
+ static NegInf() {
516
+ return Expression.Inf().neg();
517
+ }
518
+ /**
519
+ * Creates a numeric (`NUM`) expression node from a numeric representation.
520
+ *
521
+ * @remarks
522
+ * This is a low-level constructor for numeric expression nodes. The supplied value
523
+ * is stored as text and is interpreted as a {@link Rational} when the multiplier is
524
+ * first requested. Use {@link Expression.create} when the input should be parsed as
525
+ * a general mathematical expression.
526
+ *
527
+ * @param x - Numeric representation to store.
528
+ * @returns A new numeric expression.
529
+ *
530
+ * @example
531
+ * ```ts
532
+ * Expression.Number('42').text(); // "42"
533
+ * Expression.Number('3/4').text(); // "3/4"
534
+ * ```
535
+ */
536
+ static Number(x) {
537
+ return Expression.Type(String(x), NUM);
538
+ }
539
+ /**
540
+ * Creates π as a symbolic or evaluated expression.
541
+ *
542
+ * @param asNumericValue - Force the evaluated representation even when parser
543
+ * evaluation mode is disabled.
544
+ * @returns Symbolic `pi`, or its current numeric representation when evaluation is enabled.
545
+ *
546
+ * @example
547
+ * ```ts
548
+ * Expression.Pi().text(); // "pi"
549
+ * Expression.Pi(true).text(); // numeric approximation
550
+ * ```
551
+ */
552
+ static Pi(asNumericValue) {
553
+ if (Settings_1.Settings.EVALUATE || asNumericValue) {
554
+ return Expression.fromRational(Rational_1.Rational.PI);
555
+ }
556
+ return Expression.Variable(constants_1.PI[0]);
557
+ }
558
+ /**
559
+ * Sets the power of an Expression. Use this instead of assigning `power` directly.
560
+ *
561
+ * @param x - The Expression whose power to set.
562
+ * @param power - The new power Expression.
563
+ * @returns The modified Expression `x`.
564
+ */
565
+ static setPower(x, power) {
566
+ x.power = power;
567
+ return x;
568
+ }
569
+ /**
570
+ * Creates multiple Expressions at once from a list of inputs.
571
+ *
572
+ * @param values - One or more inputs to convert to Expressions.
573
+ * @returns An array of Expressions.
574
+ *
575
+ * @example
576
+ * ```ts
577
+ * const [x, y] = Expression.symbols('x', 'y');
578
+ * x.text() // "x"
579
+ * y.text() // "y"
580
+ * ```
581
+ */
582
+ static symbols(...values) {
583
+ return values.map(x => Expression.create(x));
584
+ }
585
+ /**
586
+ * Creates the internal scalar Expression used to represent symbolic bracket access.
587
+ * The formatter renders this as ordinary bracket notation rather than exposing the
588
+ * internal function name.
589
+ */
590
+ static toAccessor(target, indices) {
591
+ return Expression.toFunction(constants_1.SYMBOLIC_ACCESSOR, [target, ...indices]);
592
+ }
593
+ /**
594
+ * Constructs an `EXP` node without applying the normal power simplification rules.
595
+ *
596
+ * @remarks
597
+ * This is an internal representation helper for bases whose exponent must be stored
598
+ * separately. When `powerLess` is `true`, the existing outer power is deleted from
599
+ * the converted base before it is wrapped. Because {@link Expression.create} may
600
+ * reuse an input `Expression`, callers must not use that option when the original
601
+ * object must remain unchanged.
602
+ *
603
+ * @param x - Base to store in the `EXP` node.
604
+ * @param pow - Exponent to store on the node.
605
+ * @param powerLess - Remove an existing outer power from the base before wrapping it.
606
+ * @returns The constructed power expression, or the base itself when the base is one.
607
+ */
608
+ static toEXP(x, pow, powerLess = false) {
609
+ x = Expression.create(x);
610
+ pow = Expression.create(pow);
611
+ let retval;
612
+ // if (x.isZero() || x.isInf() || pow.isInf()) {
613
+ // retval = x.pow(pow);
614
+ // } else
615
+ if (x.isOne()) {
616
+ // Just return it untouched
617
+ retval = Expression.create(x);
618
+ }
619
+ else {
620
+ if (powerLess) {
621
+ delete x.power;
622
+ }
623
+ // The value is now the entire Expression. Consider (x^x)^(1/3).
624
+ // The value of the Expression is x^x and not x since only x^x can directly operate on it.
625
+ retval = new Expression(x.idString(), true);
626
+ retval.base = Expression.create(x);
627
+ retval.power = pow;
628
+ retval.type = EXP;
629
+ }
630
+ return retval;
631
+ }
632
+ /**
633
+ * Constructs a function node and assigns its arguments.
634
+ *
635
+ * `undefined` entries are omitted. Existing `Expression` arguments may be retained
636
+ * by identity because conversion uses {@link Expression.create} without requesting
637
+ * copies. A Vector or Matrix carrying symbolic bracket access is first normalized
638
+ * to its scalar accessor Expression; ordinary structured values remain invalid
639
+ * function arguments where an Expression is required.
640
+ *
641
+ * @param name - Function name stored on the node.
642
+ * @param args - Function arguments; `undefined` entries are ignored.
643
+ * @returns The reconstructed function expression.
644
+ */
645
+ static toFunction(name, args) {
646
+ const f = Expression.Function(name);
647
+ // Remove undefined from the array
648
+ f.args = args
649
+ .filter((x) => {
650
+ return x !== undefined;
651
+ })
652
+ .map(x => Expression.fromSymbolicAccess(x) ?? Expression.create(x));
653
+ // Set the name
654
+ f.name = name;
655
+ // TODO: This needs to be generated the same way as in text.
656
+ f.updateValue();
657
+ return f;
658
+ }
659
+ /**
660
+ * Low-level helper that creates an Expression with a specific internal type.
661
+ *
662
+ * @param x - The value string.
663
+ * @param type - The Expression type constant (NUM, VAR, FUN, EXP, etc.).
664
+ * @returns A new Expression of the specified type.
665
+ */
666
+ static Type(x, type) {
667
+ const num = new Expression(x, true);
668
+ num.type = type;
669
+ return num;
670
+ }
671
+ /**
672
+ * Creates a symbolic variable Expression.
673
+ *
674
+ * @param x - The variable name.
675
+ * @returns A `VAR`-typed Expression.
676
+ *
677
+ * @example
678
+ * ```ts
679
+ * Expression.Variable('x').text() // "x"
680
+ * ```
681
+ */
682
+ static Variable(x) {
683
+ return Expression.Type(x, VAR);
684
+ }
685
+ /**
686
+ * Returns the symbolic absolute value of this expression.
687
+ *
688
+ * The operation delegates to Nerdamer's `abs` implementation and may simplify
689
+ * values whose sign or complex magnitude can be determined.
690
+ *
691
+ * @returns The resulting expression; the receiver is not modified.
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * Expression.create(-5).abs().text(); // "5"
696
+ * Expression.create('x').abs().text(); // "abs(x)"
697
+ * ```
698
+ */
699
+ abs() {
700
+ return (0, math_1.abs)(this);
701
+ }
702
+ /**
703
+ * Legacy alias for {@link plus}.
704
+ *
705
+ * @param x - The value to add.
706
+ * @returns A new Expression representing `this + x`.
707
+ */
708
+ add(x) {
709
+ return this.plus(x);
710
+ }
711
+ /**
712
+ * Compiles this expression into a native JavaScript numeric function.
713
+ *
714
+ * @remarks
715
+ * The generated function uses JavaScript `number` arithmetic and the registered
716
+ * numerical implementations. It is intended for repeated, relatively low-precision
717
+ * scalar evaluation rather than arbitrary-precision symbolic computation. Functions
718
+ * without a faithful JavaScript-number equivalent are rejected instead of being
719
+ * compiled with approximate or unrelated semantics.
720
+ *
721
+ * When `args` is omitted, free variables are collected and sorted alphabetically.
722
+ * Supplying `args` defines the positional argument order explicitly.
723
+ *
724
+ * @param args - Variable names in the positional order expected by the compiled function.
725
+ * @returns A JavaScript function accepting numeric arguments and returning a number.
726
+ * @throws {@link core!UnsupportedOperationError} If a surviving function has no faithful
727
+ * JavaScript-number implementation.
728
+ *
729
+ * @example
730
+ * ```ts
731
+ * const fn = Expression.create('x^2 + y').buildFunction(['x', 'y']);
732
+ * fn(3, 1); // 10
733
+ * ```
734
+ */
735
+ buildFunction(args) {
736
+ return (0, build_1.build)(this, args);
737
+ }
738
+ /**
739
+ * Collects coefficients with respect to one or more requested variables.
740
+ *
741
+ * @remarks
742
+ * The expression is expanded as part of coefficient collection. For multivariate
743
+ * input, coefficient keys encode the exponent tuple in the same order as
744
+ * `variables`. Terms that do not contain a requested variable are retained as
745
+ * coefficients rather than discarded.
746
+ *
747
+ * @param variables - Variables whose powers define the coefficient keys.
748
+ * @returns Nerdamer's coefficient object for the requested variable ordering.
749
+ *
750
+ * @example
751
+ * ```ts
752
+ * const coefficients = Expression.create('3*x^2 + 2*x + 1').coeffs('x');
753
+ * coefficients.toArray().map(value => value.text()); // ["1", "2", "3"]
754
+ * ```
755
+ */
756
+ coeffs(...variables) {
757
+ return (0, analysis_1.coeffs)(this, variables);
758
+ }
759
+ /**
760
+ * Deep-copies the expression tree.
761
+ *
762
+ * @remarks
763
+ * Multipliers, powers, function arguments, explicit exponential bases, and aggregate
764
+ * elements are recursively copied. Mutating those structures on the returned
765
+ * expression therefore does not mutate the corresponding structures on the source.
766
+ *
767
+ * @returns An independently mutable expression with the same symbolic representation.
768
+ *
769
+ * @example
770
+ * ```ts
771
+ * const source = Expression.create('x + 1');
772
+ * const copy = source.copy();
773
+ *
774
+ * copy === source; // false
775
+ * copy.text(); // "1+x"
776
+ * ```
777
+ */
778
+ copy() {
779
+ return (0, utils_1.cloneExpressionTree)(this);
780
+ }
781
+ /**
782
+ * Legacy alias for {@link getDenominator}.
783
+ *
784
+ * @returns The denominator Expression.
785
+ */
786
+ denominator() {
787
+ return this.getDenominator();
788
+ }
789
+ /**
790
+ * Distributes this node's outer multiplier through a linear sum.
791
+ *
792
+ * @remarks
793
+ * A copy is created before any changes are made. Distribution is performed only
794
+ * when the expression is sum-like, has power one, and carries a non-unit outer
795
+ * multiplier. Nested sum terms encountered during the pass are handled recursively.
796
+ * Expressions that do not meet those conditions are returned as equivalent copies.
797
+ *
798
+ * @returns A new expression with the eligible multiplier distributed.
799
+ *
800
+ * @example
801
+ * ```ts
802
+ * Expression.create('2*(x+y)').distributeMultiplier().text(); // "2*x+2*y"
803
+ * ```
804
+ */
805
+ distributeMultiplier() {
806
+ const retval = this.copy();
807
+ if (this.isSum() && !this.getMultiplier().isOne() && this.isLinear()) {
808
+ const m = retval.getMultiplier();
809
+ // Remove it
810
+ retval.multiplier = undefined;
811
+ // multiply each element by the multiplier
812
+ const elements = retval.getElements();
813
+ for (const x in elements) {
814
+ const term = elements[x];
815
+ term.multiplier = term.getMultiplier().times(m);
816
+ if (term.isSum()) {
817
+ elements[x] = term.distributeMultiplier();
818
+ }
819
+ }
820
+ retval.updateValue();
821
+ }
822
+ return retval;
823
+ }
824
+ /**
825
+ * Divides this Expression by the given value.
826
+ *
827
+ * @param x - The divisor.
828
+ * @returns A new Expression representing `this / x`.
829
+ *
830
+ * @example
831
+ * ```ts
832
+ * Expression.create('x^2').div('x').text() // "x"
833
+ * Expression.create(10).div(3).text() // "10/3"
834
+ * ```
835
+ */
836
+ div(x) {
837
+ return (0, divide_1.divide)(this, Expression.create(x));
838
+ }
839
+ /**
840
+ * Legacy alias for {@link div}.
841
+ *
842
+ * @param x - The divisor.
843
+ * @returns A new Expression representing `this / x`.
844
+ */
845
+ divide(x) {
846
+ return this.div(x);
847
+ }
848
+ /**
849
+ * Visits the immediate terms represented by this expression.
850
+ *
851
+ * @remarks
852
+ * Aggregate nodes pass each stored element and its key to `fn`. Atomic nodes invoke
853
+ * the callback once with a unit-multiplier form of the expression and the node's
854
+ * value as the key. The callback's return value is ignored; this method does not
855
+ * rebuild the expression. Use {@link Expression.forEveryElement} when returned
856
+ * replacements should participate in reconstruction.
857
+ *
858
+ * For atomic nodes, creating the unit-multiplier argument does not mutate the receiver.
859
+ * Aggregate elements, however, are passed by reference, so the callback can mutate
860
+ * their internal objects if it chooses to do so.
861
+ *
862
+ * @param fn - Visitor receiving an immediate expression element and its key.
863
+ * @returns This expression for chaining.
864
+ */
865
+ each(fn) {
866
+ // The callback assumes the multiplier is carried at the top level
867
+ // So if there are no elements then call this minus the multiplier
868
+ if (!this.elements) {
869
+ fn(this.toUnitMultiplier(), this.value);
870
+ }
871
+ else {
872
+ const elements = this.getElements();
873
+ for (const x in elements) {
874
+ fn(elements[x], x);
875
+ }
876
+ }
877
+ return this;
878
+ }
879
+ /**
880
+ * Returns the immediate expression elements in canonical sort order.
881
+ *
882
+ * @remarks
883
+ * Sum-like nodes flatten nested linear sums one level while products retain nested
884
+ * sums. Atomic nodes contribute a unit-multiplier copy. When `withMultiplier` is
885
+ * `true`, a product's outer multiplier is appended as a numeric expression before
886
+ * sorting. The option has no effect on sums.
887
+ *
888
+ * Stored aggregate elements are returned by reference rather than deep-copied.
889
+ *
890
+ * @param withMultiplier - Include a product's outer coefficient as an array element.
891
+ * @returns The sorted immediate elements.
892
+ */
893
+ elementsArray(withMultiplier) {
894
+ const elementsArray = [];
895
+ if (this.isProduct() || this.isSum()) {
896
+ const elements = this.getElements();
897
+ for (const c in elements) {
898
+ const element = elements[c];
899
+ // Check for nested sums. Don't expand if we're in a product.
900
+ if (element.isSum() && this.isSum() && element.isLinear()) {
901
+ const subElements = element.getElements();
902
+ for (const sc in subElements) {
903
+ elementsArray.push(subElements[sc]);
904
+ }
905
+ }
906
+ else {
907
+ elementsArray.push(element);
908
+ }
909
+ }
910
+ }
911
+ else {
912
+ elementsArray.push(this.toUnitMultiplier());
913
+ }
914
+ // Adding the multiplier makes no sense when getting sums.
915
+ if (withMultiplier && this.isProduct()) {
916
+ elementsArray.push(Expression.fromRational(this.getMultiplier()));
917
+ }
918
+ return elementsArray.sort(Expression.sortFunction);
919
+ }
920
+ /**
921
+ * Tests whether this expression is symbolically equal to another value.
922
+ *
923
+ * @remarks
924
+ * Equality is not a JavaScript identity or raw-tree comparison. Nerdamer first
925
+ * consults applicable assumptions and otherwise subtracts the expressions,
926
+ * canonicalizes numeric radicals where needed, expands the difference, and accepts
927
+ * equality when that result reduces to numeric zero. A `false` result therefore
928
+ * means equality was not established by the current comparison machinery; it is
929
+ * not a general theorem-prover result for arbitrary symbolic identities.
930
+ *
931
+ * @param x - Value to compare with this expression.
932
+ * @returns `true` when Nerdamer establishes equality, otherwise `false`.
933
+ *
934
+ * @example
935
+ * ```ts
936
+ * Expression.create('x+1').eq('1+x'); // true
937
+ * Expression.create(3).eq(4); // false
938
+ * ```
939
+ */
940
+ eq(x) {
941
+ x = Expression.create(x);
942
+ return (0, compare_1.equal)(this, x);
943
+ }
944
+ /**
945
+ * Re-evaluates this expression numerically, optionally substituting variable values.
946
+ *
947
+ * @remarks
948
+ * Evaluation uses the ordinary serialization path. When scientific display metadata is
949
+ * present, a copy without that metadata is serialized so formatting cannot change the value sent through
950
+ * {@link Parser.evaluate}. That parser path enables Nerdamer's evaluation mode, so
951
+ * numeric constants and supported numeric functions are evaluated according to the
952
+ * parser's current precision and settings. The original expression is not modified.
953
+ *
954
+ * @param values - Variable substitutions applied during evaluation.
955
+ * @returns The evaluated expression.
956
+ *
957
+ * @example
958
+ * ```ts
959
+ * Expression.create('x^2 + 1').evaluate({ x: 3 }).text(); // "10"
960
+ * Expression.create('pi/2').evaluate().text(); // numeric approximation
961
+ * ```
962
+ */
963
+ evaluate(values) {
964
+ let source;
965
+ if (this.scientific !== undefined) {
966
+ const sourceExpression = this.copy();
967
+ delete sourceExpression.scientific;
968
+ source = sourceExpression.hasFunction(constants_1.SYMBOLIC_ACCESSOR, true)
969
+ ? (0, format_1.toText)(sourceExpression, { internalAccessor: true }, undefined, Expression.POW_OPR, Expression.sortFunction)
970
+ : sourceExpression.text();
971
+ }
972
+ else {
973
+ source = this.hasFunction(constants_1.SYMBOLIC_ACCESSOR, true)
974
+ ? (0, format_1.toText)(this, { internalAccessor: true }, undefined, Expression.POW_OPR, Expression.sortFunction)
975
+ : this.text();
976
+ }
977
+ const evaluated = Parser_1.Parser.evaluate(source, values);
978
+ const retval = Expression.fromSymbolicAccess(evaluated) ?? Expression.create(evaluated);
979
+ if (this.scientific !== undefined) {
980
+ retval.scientific = this.scientific;
981
+ }
982
+ return retval;
983
+ }
984
+ /**
985
+ * Expands products and eligible powers into an equivalent symbolic expression.
986
+ *
987
+ * @remarks
988
+ * Expansion delegates to Nerdamer's canonical expansion algorithm. The result is
989
+ * independent of the receiver, but callers should treat object identity as an
990
+ * implementation detail rather than relying on expansion to allocate a particular
991
+ * representation. Branch-sensitive power rules are preserved rather than treating
992
+ * every algebraic power identity as universally valid over the complex domain.
993
+ *
994
+ * @returns The expanded expression.
995
+ *
996
+ * @example
997
+ * ```ts
998
+ * Expression.create('(x+1)^2').expand().text(); // "1+2*x+x^2"
999
+ * ```
1000
+ */
1001
+ expand() {
1002
+ return (0, expand_1.expand)(this);
1003
+ }
1004
+ /**
1005
+ * Applies a transformation while recursively rebuilding this expression.
1006
+ *
1007
+ * @remarks
1008
+ * Unlike {@link Expression.each}, callback results are used as replacements. The
1009
+ * traversal reconstructs functions, products, sums, and exponential powers while
1010
+ * restoring the original outer multiplier and power. Numeric and variable roots are
1011
+ * returned unchanged by the traversal helper rather than passed through `fn`, so the
1012
+ * result may preserve the receiver's identity for those atomic cases.
1013
+ *
1014
+ * @param fn - Transformation applied to traversed symbolic components.
1015
+ * @returns The rebuilt expression.
1016
+ */
1017
+ forEveryElement(fn) {
1018
+ return (0, traversal_3.forEveryElement)(this, fn);
1019
+ }
1020
+ /**
1021
+ * Collects distinct function occurrences from the expression tree.
1022
+ *
1023
+ * @remarks
1024
+ * By default the returned strings are function names such as `sin` and `cos`.
1025
+ * When `getValues` is `true`, the collector instead returns each function node's
1026
+ * stored value string, such as `sin(x)`, while still deduplicating repeated values.
1027
+ * Traversal includes function arguments, aggregate elements, and `EXP` bases and
1028
+ * powers.
1029
+ *
1030
+ * If `fns` is supplied, results are appended to that same array.
1031
+ *
1032
+ * @param fns - Optional accumulator that receives unique strings.
1033
+ * @param getValues - Collect stored function-expression strings instead of names.
1034
+ * @returns The accumulator containing the collected function strings.
1035
+ *
1036
+ * @example
1037
+ * ```ts
1038
+ * Expression.create('sin(x) + cos(y)').functions(); // ["sin", "cos"]
1039
+ * ```
1040
+ */
1041
+ functions(fns, getValues) {
1042
+ return (0, traversal_2.functions)(this, fns, getValues);
1043
+ }
1044
+ /**
1045
+ * Returns the mutable argument array stored by this function node.
1046
+ *
1047
+ * @remarks
1048
+ * The array is lazily created when no arguments are present and is returned by
1049
+ * reference, not copied. Mutating the returned array therefore mutates this
1050
+ * expression. Call {@link Expression.updateValue} after structural changes when
1051
+ * the stored `value` string must be regenerated.
1052
+ *
1053
+ * @returns The internal function-argument array.
1054
+ *
1055
+ * @example
1056
+ * ```ts
1057
+ * Expression.create('sin(x)').getArguments()[0].text(); // "x"
1058
+ * ```
1059
+ */
1060
+ getArguments() {
1061
+ if (!this.args) {
1062
+ this.args = [];
1063
+ }
1064
+ return this.args;
1065
+ }
1066
+ /**
1067
+ * Returns the mathematical base represented by this node.
1068
+ *
1069
+ * @remarks
1070
+ * `EXP` nodes return their stored base directly because signs and coefficients that
1071
+ * belong inside an exponential base must remain part of that base. Other node types
1072
+ * derive the same base from a deep structural copy with the outer multiplier and
1073
+ * outer power removed.
1074
+ *
1075
+ * The `EXP` branch returns the internal base by reference. The non-`EXP` branch
1076
+ * returns an independent expression and does not re-enter the parser.
1077
+ *
1078
+ * @returns The stored or derived base expression.
1079
+ *
1080
+ * @example
1081
+ * ```ts
1082
+ * Expression.create('3*x^2').getBase().text(); // "x"
1083
+ * Expression.create('2^(x+1)').getBase().text(); // "2"
1084
+ * ```
1085
+ */
1086
+ getBase() {
1087
+ let retval;
1088
+ if (this.isEXP()) {
1089
+ retval = this.base;
1090
+ }
1091
+ else {
1092
+ retval = this.copy();
1093
+ delete retval.multiplier;
1094
+ delete retval.power;
1095
+ }
1096
+ return retval;
1097
+ }
1098
+ /**
1099
+ * Extracts the denominator represented by this expression's current structure.
1100
+ *
1101
+ * @remarks
1102
+ * The operation collects the rational multiplier's denominator and factors carried
1103
+ * by negative powers in a product. It does not first combine a sum over a common
1104
+ * denominator. For example, `a/x + 8` is a sum whose outer denominator is one, while
1105
+ * the individual term `a/x` has denominator `x`.
1106
+ *
1107
+ * @returns The denominator represented by the current expression structure.
1108
+ *
1109
+ * @example
1110
+ * ```ts
1111
+ * Expression.create('x/y').getDenominator().text() // "y"
1112
+ * Expression.create('3/4').getDenominator().text() // "4"
1113
+ * ```
1114
+ */
1115
+ getDenominator() {
1116
+ return (0, analysis_3.getDenominator)(this);
1117
+ }
1118
+ /**
1119
+ * Returns the mutable child-element record stored by an aggregate expression.
1120
+ *
1121
+ * @remarks
1122
+ * When `elements` exists, the actual internal record is returned rather than a copy.
1123
+ * Mutating it therefore mutates this expression and can invalidate canonical keys or
1124
+ * the stored `value` string unless the caller restores the corresponding representation state. When this
1125
+ * node has no element record, a new empty object is returned and is not attached to
1126
+ * the expression.
1127
+ *
1128
+ * @returns The internal element record, or a detached empty record for atomic nodes.
1129
+ */
1130
+ getElements() {
1131
+ if (!this.elements) {
1132
+ return {};
1133
+ }
1134
+ return this.elements;
1135
+ }
1136
+ getMultiplier(asExpression) {
1137
+ if (this.multiplier === undefined) {
1138
+ const value = this.type === NUM ? this.value : '1';
1139
+ this.multiplier = Rational_1.Rational.create(value);
1140
+ }
1141
+ if (asExpression) {
1142
+ return Expression.create(this.multiplier);
1143
+ }
1144
+ return this.multiplier;
1145
+ }
1146
+ /**
1147
+ * Extracts the numerator represented by this expression's current structure.
1148
+ *
1149
+ * @remarks
1150
+ * The operation separates the numerator of the rational multiplier and recursively
1151
+ * collects numerator factors from linear products. It does not first rewrite a sum
1152
+ * over a common denominator; a sum such as `a/x + 8` therefore remains the numerator
1153
+ * of that top-level representation.
1154
+ *
1155
+ * @returns The numerator represented by the current expression structure.
1156
+ *
1157
+ * @example
1158
+ * ```ts
1159
+ * Expression.create('x/y').getNumerator().text() // "x"
1160
+ * Expression.create('3/4').getNumerator().text() // "3"
1161
+ * ```
1162
+ */
1163
+ getNumerator() {
1164
+ return (0, analysis_3.getNumerator)(this);
1165
+ }
1166
+ /**
1167
+ * Returns this node's effective outer power.
1168
+ *
1169
+ * @remarks
1170
+ * The power is initialized lazily and stored on the expression. Numeric (`NUM`)
1171
+ * nodes default to power zero because their numeric value is carried by the
1172
+ * multiplier; other node types default to power one. The returned `Expression` is
1173
+ * the mutable internal power object, not a copy.
1174
+ *
1175
+ * @returns The internal power expression.
1176
+ *
1177
+ * @example
1178
+ * ```ts
1179
+ * Expression.create('x^3').getPower().text(); // "3"
1180
+ * Expression.create('x').getPower().text(); // "1"
1181
+ * ```
1182
+ */
1183
+ getPower() {
1184
+ if (!this.power) {
1185
+ // Don't use shortcuts as this power may later be modified.
1186
+ if (this.isNUM()) {
1187
+ this.power = Expression.Number('0');
1188
+ }
1189
+ else {
1190
+ this.power = Expression.Number('1');
1191
+ }
1192
+ }
1193
+ return this.power;
1194
+ }
1195
+ /**
1196
+ * Retrieves a matching variable factor from this node.
1197
+ *
1198
+ * The method returns this expression when its stored value matches `variable`, or
1199
+ * the matching immediate factor when this is a product. When no match is found it
1200
+ * returns the numeric zero expression rather than `undefined`.
1201
+ *
1202
+ * @param variable - Stored variable value to locate.
1203
+ * @returns The matching expression reference, or zero when no match exists.
1204
+ */
1205
+ getVariable(variable) {
1206
+ return (0, analysis_2.getVariable)(this, variable);
1207
+ }
1208
+ /**
1209
+ * Tests whether this expression is `>` another value.
1210
+ *
1211
+ * @remarks
1212
+ * Nerdamer consults applicable assumptions and otherwise evaluates the difference
1213
+ * numerically/symbolically. These `Expression` comparison methods remain boolean for
1214
+ * compatibility. An unknown assumption result falls through to the ordinary comparison
1215
+ * path; if the relation still cannot be established, the method returns `false`. The
1216
+ * lower-level `Assumption` relations preserve unknown as `undefined`. Complex values are
1217
+ * not ordered and cause the comparison to throw.
1218
+ *
1219
+ * @param x - Value to compare with this expression.
1220
+ * @returns `true` when the requested ordering is established, otherwise `false`.
1221
+ * @throws {@link core!UnsupportedOperationError}
1222
+ * Thrown when either side is classified as complex.
1223
+ */
1224
+ gt(x) {
1225
+ x = Expression.create(x);
1226
+ return (0, compare_1.gt)(this, x);
1227
+ }
1228
+ /**
1229
+ * Tests whether this expression is `>=` another value.
1230
+ *
1231
+ * @remarks
1232
+ * Nerdamer consults applicable assumptions and otherwise evaluates the difference
1233
+ * numerically/symbolically. These `Expression` comparison methods remain boolean for
1234
+ * compatibility. An unknown assumption result falls through to the ordinary comparison
1235
+ * path; if the relation still cannot be established, the method returns `false`. The
1236
+ * lower-level `Assumption` relations preserve unknown as `undefined`. Complex values are
1237
+ * not ordered and cause the comparison to throw.
1238
+ *
1239
+ * @param x - Value to compare with this expression.
1240
+ * @returns `true` when the requested ordering is established, otherwise `false`.
1241
+ * @throws {@link core!UnsupportedOperationError}
1242
+ * Thrown when either side is classified as complex.
1243
+ */
1244
+ gte(x) {
1245
+ x = Expression.create(x);
1246
+ return (0, compare_1.gte)(this, x);
1247
+ }
1248
+ /**
1249
+ * Reports whether decimal-origin numeric data occurs anywhere in this expression.
1250
+ *
1251
+ * @remarks
1252
+ * The check follows the multiplier, explicit power, exponential base, function
1253
+ * arguments, and aggregate elements. It tests the rational `asDecimal` provenance
1254
+ * marker; it does not merely search rendered text for a decimal point.
1255
+ *
1256
+ * @returns `true` when any contained rational originated from decimal input.
1257
+ */
1258
+ hasDecimal() {
1259
+ let retval = this.getMultiplier().asDecimal;
1260
+ if (!retval && this.power) {
1261
+ retval = this.power.hasDecimal();
1262
+ }
1263
+ if (!retval && this.base) {
1264
+ retval = this.base.hasDecimal();
1265
+ }
1266
+ if (!retval && this.args) {
1267
+ retval = this.args.some(argument => argument.hasDecimal());
1268
+ }
1269
+ if (!retval && this.elements) {
1270
+ retval = Object.values(this.elements).some(element => element.hasDecimal());
1271
+ }
1272
+ return retval;
1273
+ }
1274
+ /**
1275
+ * Tests whether a named function occurs in this expression.
1276
+ *
1277
+ * @remarks
1278
+ * Aggregate elements are always searched. When `deep` is `true`, function arguments
1279
+ * and the explicit base and power of `EXP` nodes are searched recursively as well.
1280
+ * With `deep` disabled, nested function arguments and `EXP` components are not
1281
+ * traversed.
1282
+ *
1283
+ * @param name - Function name to locate.
1284
+ * @param deep - Include function arguments and `EXP` base/power traversal.
1285
+ * @returns `true` when the named function is found.
1286
+ */
1287
+ hasFunction(name, deep = false) {
1288
+ return (0, traversal_1.hasFunction)(this, name, deep);
1289
+ }
1290
+ /**
1291
+ * Tests the node's outer power for a rational exponent with a non-unit denominator.
1292
+ *
1293
+ * @remarks
1294
+ * This predicate examines this node's effective power; it does not recursively scan
1295
+ * every descendant for radicals. When `checkIrrationalDenominator` is `true`, the
1296
+ * power must also be negative, which identifies a radical occurring in a denominator.
1297
+ *
1298
+ * @param checkIrrationalDenominator - Require the fractional power to be negative.
1299
+ * @returns `true` when the outer power meets the requested radical condition.
1300
+ */
1301
+ hasRadical(checkIrrationalDenominator) {
1302
+ const p = this.getPower();
1303
+ const m = p.getMultiplier();
1304
+ const isRadical = p.isNUM() && m.denominator !== 1n;
1305
+ if (checkIrrationalDenominator) {
1306
+ return isRadical && m.isNegative();
1307
+ }
1308
+ return isRadical;
1309
+ }
1310
+ /**
1311
+ * Tests whether a variable node with the requested value occurs in the expression tree.
1312
+ *
1313
+ * Function arguments, aggregate elements, and `EXP` bases and powers are searched
1314
+ * recursively. This predicate does not apply the free-variable filtering used by
1315
+ * {@link Expression.variables}; reserved constants can still match when requested
1316
+ * explicitly.
1317
+ *
1318
+ * @param variable - Variable value to locate.
1319
+ * @returns `true` when a matching `VAR` node occurs.
1320
+ */
1321
+ hasVariable(variable) {
1322
+ return (0, traversal_1.hasVariable)(this, variable);
1323
+ }
1324
+ /**
1325
+ * Multiplies this Expression by the imaginary unit, converting it to an imaginary value.
1326
+ *
1327
+ * @returns A new Expression equal to `this * i`.
1328
+ *
1329
+ * @example
1330
+ * ```ts
1331
+ * Expression.create(3).i().text() // "3*i"
1332
+ * ```
1333
+ */
1334
+ i() {
1335
+ return this.times(Expression.Img());
1336
+ }
1337
+ /**
1338
+ * Returns a string representation used internally for structural comparison
1339
+ * of expressions.
1340
+ *
1341
+ * @returns A string identifier suitable for equality checks.
1342
+ */
1343
+ idString() {
1344
+ return this.text(undefined, true);
1345
+ }
1346
+ /**
1347
+ * Returns Nerdamer's symbolic decomposition of the imaginary component.
1348
+ *
1349
+ * @remarks
1350
+ * The result excludes the imaginary-unit factor itself. Decomposition follows
1351
+ * principal-branch handling for powered complex values and preserves unresolved
1352
+ * complex function components symbolically instead of silently treating them as
1353
+ * zero. `realpart(...)` and `imagpart(...)` nodes are treated as real-valued component
1354
+ * expressions.
1355
+ *
1356
+ * @returns The symbolic imaginary coefficient.
1357
+ */
1358
+ imagPart() {
1359
+ return (0, complex_1.imagPart)(this);
1360
+ }
1361
+ /**
1362
+ * Returns the multiplicative inverse of this expression.
1363
+ *
1364
+ * @remarks
1365
+ * Real symbolic nodes are copied and inverted by negating the outer power and
1366
+ * rational multiplier. Complex expressions use the general division path so real and
1367
+ * imaginary components are handled correctly. Simple radical denominators are
1368
+ * rationalized when the power operation identifies an eligible radical.
1369
+ *
1370
+ * The receiver is not modified.
1371
+ *
1372
+ * @returns The reciprocal expression.
1373
+ * @throws {@link core!DivisionByZeroError}
1374
+ * Thrown by the underlying rational or division operation when the expression is zero.
1375
+ */
1376
+ invert() {
1377
+ let retval;
1378
+ if (this.isComplex()) {
1379
+ retval = (0, shortcuts_1.one)().div(this);
1380
+ }
1381
+ else {
1382
+ retval = this.copy();
1383
+ retval.power = retval.getPower().neg();
1384
+ retval.multiplier = retval.getMultiplier().invert();
1385
+ }
1386
+ if (retval.hasRadical()) {
1387
+ return (0, power_2.rationalizeRadical)(retval);
1388
+ }
1389
+ return retval;
1390
+ }
1391
+ /**
1392
+ * Reports whether the current expression tree contains a complex-valued component.
1393
+ *
1394
+ * @remarks
1395
+ * The check is structural: it recognizes the current imaginary-unit symbol, recurses
1396
+ * through function arguments, `EXP` bases and powers, and aggregate elements. The
1397
+ * component functions `realpart(...)` and `imagpart(...)` are treated as real-valued
1398
+ * by definition even when their arguments contain complex values.
1399
+ *
1400
+ * This predicate does not impose an ordering or otherwise claim that an unrestricted
1401
+ * symbolic expression is provably real.
1402
+ *
1403
+ * @returns `true` when the represented expression contains a recognized complex component.
1404
+ */
1405
+ isComplex() {
1406
+ let retval = false;
1407
+ if (this.isFunction(constants_1.SYMBOLIC_ACCESSOR)) {
1408
+ // Accessor arguments identify a selected value; they are not arithmetic
1409
+ // components of that value. In particular, an index named `i` must not
1410
+ // make an unresolved access appear complex merely because `i` is also the
1411
+ // configured imaginary-unit symbol.
1412
+ retval = false;
1413
+ }
1414
+ else if (!this.isComplexComponentFunction()) {
1415
+ if (this.isVAR() && this.isI()) {
1416
+ retval = true;
1417
+ }
1418
+ else if (this.isFunction()) {
1419
+ for (const argument of this.getArguments()) {
1420
+ if (argument.isComplex()) {
1421
+ retval = true;
1422
+ break;
1423
+ }
1424
+ }
1425
+ }
1426
+ else if (this.isEXP()) {
1427
+ retval = this.getBase().isComplex() || this.getPower().isComplex();
1428
+ }
1429
+ else if (this.elements) {
1430
+ for (const element of Object.values(this.getElements())) {
1431
+ if (element.isComplex()) {
1432
+ retval = true;
1433
+ break;
1434
+ }
1435
+ }
1436
+ }
1437
+ }
1438
+ return retval;
1439
+ }
1440
+ /**
1441
+ * Tests whether this node is `realpart(...)` or `imagpart(...)`.
1442
+ *
1443
+ * These component functions are treated as real-valued by the complex-decomposition
1444
+ * logic even when their arguments are complex.
1445
+ */
1446
+ isComplexComponentFunction() {
1447
+ return this.isFunction([constants_1.REALPART, constants_1.IMAGPART]);
1448
+ }
1449
+ /**
1450
+ * Tests whether this node belongs to Nerdamer's currently recognized constant forms.
1451
+ *
1452
+ * @remarks
1453
+ * This is narrower than the mathematical statement "contains no free
1454
+ * variables." It recognizes numeric nodes, parser constants such as `pi` and `e`,
1455
+ * constant-base/constant-power `EXP` nodes, and sums or products whose elements are
1456
+ * recursively recognized as constant. The imaginary unit is handled by
1457
+ * dedicated complex logic rather than classified here as a parser constant.
1458
+ *
1459
+ * Do not use this predicate as a general proof that an arbitrary function expression
1460
+ * is or is not mathematically constant.
1461
+ *
1462
+ * @returns `true` for the constant forms recognized by this predicate.
1463
+ */
1464
+ isConstant() {
1465
+ if (this.isSum() || this.isProduct()) {
1466
+ const elements = this.getElements();
1467
+ for (const x in elements) {
1468
+ if (!elements[x].isConstant()) {
1469
+ return false;
1470
+ }
1471
+ }
1472
+ return true;
1473
+ }
1474
+ return (this.isNUM() ||
1475
+ // Test for cases like pi & e
1476
+ (this.value in constants_1.PARSER_CONSTANTS && this.isVAR()) ||
1477
+ // Test for cases like 3^(1/2)
1478
+ (this.isEXP() && this.getBase().isConstant() && this.getPower().isConstant()));
1479
+ }
1480
+ /**
1481
+ * Tests whether this node's stored value is the Euler-constant symbol `e`.
1482
+ *
1483
+ * The check is representation-level and does not require a unit multiplier or power.
1484
+ *
1485
+ * @returns `true` when `value` is the current `e` symbol.
1486
+ */
1487
+ isE() {
1488
+ return this.value === constants_1.E;
1489
+ }
1490
+ /**
1491
+ * Checks whether this Expression is an even integer.
1492
+ *
1493
+ * @returns `true` if the expression is `NUM` and its multiplier is even.
1494
+ *
1495
+ * @example
1496
+ * ```ts
1497
+ * Expression.create(4).isEven() // true
1498
+ * Expression.create(3).isEven() // false
1499
+ * ```
1500
+ */
1501
+ isEven() {
1502
+ return this.isNUM() && this.getMultiplier().isEven();
1503
+ }
1504
+ /**
1505
+ * Checks whether this Expression has the EXP (exponential/power) internal type.
1506
+ *
1507
+ * @returns `true` if the type is EXP.
1508
+ */
1509
+ isEXP() {
1510
+ return this.type === EXP;
1511
+ }
1512
+ isFunction(names) {
1513
+ let retval;
1514
+ if (names === undefined) {
1515
+ retval = this.type === FUN;
1516
+ }
1517
+ else if (typeof names === 'string') {
1518
+ retval = names === this.name;
1519
+ }
1520
+ else {
1521
+ retval = names.includes(String(this.name));
1522
+ }
1523
+ return retval;
1524
+ }
1525
+ /**
1526
+ * Checks whether this Expression is exactly `1/2`.
1527
+ *
1528
+ * @returns `true` if the expression is the numeric value `1/2`.
1529
+ */
1530
+ isHalf() {
1531
+ if (this.isNUM()) {
1532
+ const m = this.getMultiplier();
1533
+ return m.numerator === 1n && m.denominator === 2n;
1534
+ }
1535
+ return false;
1536
+ }
1537
+ /**
1538
+ * Tests whether this node's stored value is the current imaginary-unit symbol.
1539
+ *
1540
+ * @remarks
1541
+ * This is a representation-level symbol check. It does not require the node to have
1542
+ * multiplier one or power one, so callers that require exactly the mathematical unit
1543
+ * `i` must impose those additional conditions themselves.
1544
+ *
1545
+ * @returns `true` when `value` matches {@link Expression.imaginary}.
1546
+ */
1547
+ isI() {
1548
+ return this.value === Expression.imaginary;
1549
+ }
1550
+ /**
1551
+ * Evaluates the expression and reports whether the result is classified as complex.
1552
+ *
1553
+ * @remarks
1554
+ * Despite the historical method name, this is not a test for a purely imaginary
1555
+ * value with zero real part. A value such as `3 + 2*i` also returns `true` because
1556
+ * the evaluated result contains a complex component.
1557
+ *
1558
+ * @returns `true` when the evaluated expression satisfies {@link Expression.isComplex}.
1559
+ */
1560
+ isImaginary() {
1561
+ return this.evaluate().isComplex();
1562
+ }
1563
+ /**
1564
+ * Checks whether this Expression represents infinity (positive or negative).
1565
+ *
1566
+ * @returns `true` if the type is INF.
1567
+ */
1568
+ isInf() {
1569
+ return this.type === INF;
1570
+ }
1571
+ /**
1572
+ * Checks whether this Expression is an exact integer.
1573
+ *
1574
+ * @returns `true` if the expression is `NUM` with an integer multiplier.
1575
+ *
1576
+ * @example
1577
+ * ```ts
1578
+ * Expression.create(5).isInteger() // true
1579
+ * Expression.create('3/2').isInteger() // false
1580
+ * ```
1581
+ */
1582
+ isInteger() {
1583
+ if (this.isOne()) {
1584
+ return true;
1585
+ }
1586
+ return this.type === NUM && this.getMultiplier().isInteger();
1587
+ }
1588
+ /**
1589
+ * Checks whether this Expression has power equal to `1` (i.e. is linear in itself).
1590
+ *
1591
+ * @returns `true` if the power is `1`.
1592
+ */
1593
+ isLinear() {
1594
+ return this.getPower().isOne();
1595
+ }
1596
+ /**
1597
+ * Checks whether this Expression is exactly `-1`.
1598
+ *
1599
+ * @returns `true` if the expression equals `-1`.
1600
+ */
1601
+ isMinusOne() {
1602
+ // Avoid creating an object if not needed
1603
+ if (this.isNUM()) {
1604
+ if (this.multiplier === undefined && Number(this.value) === -1) {
1605
+ return true;
1606
+ }
1607
+ return this.getMultiplier().isMinusOne();
1608
+ }
1609
+ return false;
1610
+ }
1611
+ /**
1612
+ * Tests whether both evaluated complex components are small relative to Decimal precision.
1613
+ *
1614
+ * @remarks
1615
+ * The tolerance is `10^(-Decimal.precision + k)`. This is a numerical-algorithm
1616
+ * convenience and must not be used as a replacement for exact symbolic zero testing;
1617
+ * use {@link Expression.isZero} when exact representation-level zero is required.
1618
+ *
1619
+ * @param k - Number of guard digits removed from the active Decimal precision.
1620
+ * @returns `true` when the magnitudes of both real and imaginary components are within the tolerance.
1621
+ */
1622
+ isNearlyZero(k = 8) {
1623
+ const eps = new decimal_js_1.default(10).pow(-decimal_js_1.default.precision + k);
1624
+ const re = this.realPart();
1625
+ const im = this.imagPart();
1626
+ return re.abs().lte(eps) && im.abs().lte(eps);
1627
+ }
1628
+ /**
1629
+ * Tests whether this expression is established to be strictly less than zero.
1630
+ *
1631
+ * The result follows {@link Expression.lt}: unresolved symbolic sign information
1632
+ * currently produces `false`, while complex values cannot be ordered.
1633
+ *
1634
+ * @returns `true` when the current comparison machinery establishes a negative value.
1635
+ * @throws {@link core!UnsupportedOperationError}
1636
+ * Thrown when the expression is classified as complex.
1637
+ */
1638
+ isNegative() {
1639
+ return this.lt((0, shortcuts_1.zero)());
1640
+ }
1641
+ /**
1642
+ * Checks whether this Expression is negative infinity (`−∞`).
1643
+ *
1644
+ * @returns `true` if the expression is `−∞`.
1645
+ */
1646
+ isNegInf() {
1647
+ return this.isInf() && this.getMultiplier().lt('0');
1648
+ }
1649
+ /**
1650
+ * Checks whether this Expression has the `NUM` (numeric) internal type.
1651
+ *
1652
+ * This only matches explicit numbers, not symbolic constants like `pi` or `e`.
1653
+ * Use {@link isConstant} to check for all values that reduce to a constant.
1654
+ *
1655
+ * @returns `true` if the type is `NUM`.
1656
+ *
1657
+ * @example
1658
+ * ```ts
1659
+ * Expression.create(5).isNUM() // true
1660
+ * Expression.create('pi').isNUM() // false
1661
+ * ```
1662
+ */
1663
+ isNUM() {
1664
+ return this.type === NUM;
1665
+ }
1666
+ /**
1667
+ * Tests whether this Expression is represented as a plain numeric value.
1668
+ *
1669
+ * @returns `true` for NUM expressions.
1670
+ */
1671
+ isNumber() {
1672
+ return this.isNUM();
1673
+ }
1674
+ /**
1675
+ * Checks whether this Expression is an odd integer.
1676
+ *
1677
+ * @returns `true` only for numeric integer expressions whose multiplier is odd.
1678
+ */
1679
+ isOdd() {
1680
+ return this.isInteger() && !this.isEven();
1681
+ }
1682
+ /**
1683
+ * Checks whether this Expression is exactly `1`.
1684
+ *
1685
+ * @returns `true` if the expression equals `1`.
1686
+ */
1687
+ isOne() {
1688
+ // Avoid creating an object if not needed
1689
+ if (this.isNUM()) {
1690
+ const m = this.getMultiplier();
1691
+ return m.numerator === 1n && m.denominator === 1n;
1692
+ }
1693
+ return false;
1694
+ }
1695
+ /**
1696
+ * Tests whether this node's stored value matches a recognized π symbol.
1697
+ *
1698
+ * The check is representation-level and does not require a unit multiplier or power.
1699
+ *
1700
+ * @returns `true` when `value` is one of Nerdamer's π aliases.
1701
+ */
1702
+ isPi() {
1703
+ return constants_1.PI.includes(this.value);
1704
+ }
1705
+ /**
1706
+ * Checks whether this Expression is a plain variable with no multiplier and
1707
+ * no power (i.e. multiplier `1`, power `1`, type `VAR`).
1708
+ *
1709
+ * @returns `true` for a bare variable like `x`.
1710
+ *
1711
+ * @example
1712
+ * ```ts
1713
+ * Expression.create('x').isPlainVariable() // true
1714
+ * Expression.create('2*x').isPlainVariable() // false
1715
+ * Expression.create('x^2').isPlainVariable() // false
1716
+ * ```
1717
+ */
1718
+ isPlainVariable() {
1719
+ return this.isVAR() && this.getMultiplier().isOne() && this.getPower().isOne();
1720
+ }
1721
+ /**
1722
+ * Tests whether this expression has the structural form of a polynomial over rational coefficients.
1723
+ *
1724
+ * @remarks
1725
+ * The predicate accepts recursively composed sums and products whose outer powers are
1726
+ * non-negative integers. Function nodes, `EXP` nodes, infinities, negative powers,
1727
+ * and fractional powers are rejected. This is a structural eligibility check used by
1728
+ * polynomial-oriented algorithms; it does not construct a {@link algebra!Polynomial}.
1729
+ *
1730
+ * @returns `true` when the expression satisfies the current polynomial-like restrictions.
1731
+ */
1732
+ isPolynomialLike() {
1733
+ return (0, analysis_2.isPolynomialLike)(this);
1734
+ }
1735
+ /**
1736
+ * Checks whether this Expression is positive infinity (`+∞`).
1737
+ *
1738
+ * @returns `true` if the expression is `+∞`.
1739
+ */
1740
+ isPosInf() {
1741
+ return this.isInf() && this.getMultiplier().gt((0, shortcuts_1.zero)());
1742
+ }
1743
+ /**
1744
+ * Checks whether this Expression has the PRD (product) internal type.
1745
+ *
1746
+ * @returns `true` if the type is PRD.
1747
+ */
1748
+ isProduct() {
1749
+ return this.type === PRD;
1750
+ }
1751
+ /**
1752
+ * Checks whether this Expression is exactly `1/4`.
1753
+ *
1754
+ * @returns `true` if the expression is the numeric value `1/4`.
1755
+ */
1756
+ isQuarter() {
1757
+ if (this.isNUM()) {
1758
+ const m = this.getMultiplier();
1759
+ return m.numerator === 1n && m.denominator === 4n;
1760
+ }
1761
+ return false;
1762
+ }
1763
+ /**
1764
+ * Checks whether this Expression is a summation-like type (SUM or GRP).
1765
+ *
1766
+ * @returns `true` if the type is SUM or GRP.
1767
+ */
1768
+ isSum() {
1769
+ return this.type === SUM || this.type === GRP;
1770
+ }
1771
+ /**
1772
+ * Checks whether this Expression has the VAR (variable) internal type.
1773
+ *
1774
+ * @returns `true` if the type is VAR.
1775
+ */
1776
+ isVAR() {
1777
+ return this.type === VAR;
1778
+ }
1779
+ /**
1780
+ * Checks whether this Expression is exactly `0`.
1781
+ *
1782
+ * @returns `true` if the multiplier is zero.
1783
+ *
1784
+ * @example
1785
+ * ```ts
1786
+ * Expression.create(0).isZero() // true
1787
+ * Expression.create(1).isZero() // false
1788
+ * ```
1789
+ */
1790
+ isZero() {
1791
+ return this.getMultiplier().isZero();
1792
+ }
1793
+ /**
1794
+ * Builds the canonical lookup key used to group compatible expression terms.
1795
+ *
1796
+ * @remarks
1797
+ * This is an internal canonicalization key, not a user-facing serialization format.
1798
+ * Numeric nodes normally collapse to {@link Expression.numberHash}; variables,
1799
+ * functions, exponentials, and infinities use multiplier-free identifiers; aggregate
1800
+ * nodes derive a key from their canonical elements. Group (`GRP`) handling can use the
1801
+ * power directly when `isGroup` is requested.
1802
+ *
1803
+ * The exact key format is coupled to parser/algebra combination logic and should not
1804
+ * be persisted as an external interchange format.
1805
+ *
1806
+ * @param asSubExpression - Use the fuller sub-expression representation where supported.
1807
+ * @param isGroup - Build a group-member key from this expression's power.
1808
+ * @returns The canonical lookup key.
1809
+ * @throws Error
1810
+ * Thrown when no key-generation rule exists for the node's internal type.
1811
+ */
1812
+ keyValue(asSubExpression = false, isGroup = false) {
1813
+ const cacheable = !asSubExpression && !isGroup && (this.type === SUM || this.type === PRD);
1814
+ if (cacheable && this._keyValueCache !== undefined) {
1815
+ return this._keyValueCache;
1816
+ }
1817
+ let retval = '';
1818
+ // For GRP the key is always the power
1819
+ if (isGroup) {
1820
+ retval = this.getPower().text();
1821
+ }
1822
+ else {
1823
+ switch (this.type) {
1824
+ case NUM:
1825
+ // If we're appending we need the hash. However when generating a hash, we want the actual value.
1826
+ retval = asSubExpression ? this.value : Expression.numberHash;
1827
+ break;
1828
+ case VAR:
1829
+ case FUN:
1830
+ case EXP:
1831
+ case INF:
1832
+ // Return the id string since we don't want the multiplier for comparison.
1833
+ retval = asSubExpression ? this.idString() : this.value;
1834
+ break;
1835
+ case GRP:
1836
+ retval = asSubExpression
1837
+ ? this.text()
1838
+ : Object.values(this.getElements())[0].keyValue();
1839
+ break;
1840
+ case SUM:
1841
+ case PRD:
1842
+ // e.g. (1+x) can only directly operate on (1+x) and not (1+2*x), (2+x), etc without inspecting each one
1843
+ retval = Expression.getValue(Object.values(this.getElements()), 'text', this.type);
1844
+ break;
1845
+ }
1846
+ }
1847
+ if (!retval) {
1848
+ throw new Error((0, errors_1.message)('expressionKeyValueUnsupported', { type: String(this.type) }));
1849
+ }
1850
+ if (cacheable) {
1851
+ this._keyValueCache = retval;
1852
+ }
1853
+ return retval;
1854
+ }
1855
+ /**
1856
+ * Tests whether this expression is `<` another value.
1857
+ *
1858
+ * @remarks
1859
+ * Nerdamer consults applicable assumptions and otherwise evaluates the difference
1860
+ * numerically/symbolically. These `Expression` comparison methods remain boolean for
1861
+ * compatibility. An unknown assumption result falls through to the ordinary comparison
1862
+ * path; if the relation still cannot be established, the method returns `false`. The
1863
+ * lower-level `Assumption` relations preserve unknown as `undefined`. Complex values are
1864
+ * not ordered and cause the comparison to throw.
1865
+ *
1866
+ * @param x - Value to compare with this expression.
1867
+ * @returns `true` when the requested ordering is established, otherwise `false`.
1868
+ * @throws {@link core!UnsupportedOperationError}
1869
+ * Thrown when either side is classified as complex.
1870
+ */
1871
+ lt(x) {
1872
+ x = Expression.create(x);
1873
+ return (0, compare_1.lt)(this, x);
1874
+ }
1875
+ /**
1876
+ * Tests whether this expression is `<=` another value.
1877
+ *
1878
+ * @remarks
1879
+ * Nerdamer consults applicable assumptions and otherwise evaluates the difference
1880
+ * numerically/symbolically. These `Expression` comparison methods remain boolean for
1881
+ * compatibility. An unknown assumption result falls through to the ordinary comparison
1882
+ * path; if the relation still cannot be established, the method returns `false`. The
1883
+ * lower-level `Assumption` relations preserve unknown as `undefined`. Complex values are
1884
+ * not ordered and cause the comparison to throw.
1885
+ *
1886
+ * @param x - Value to compare with this expression.
1887
+ * @returns `true` when the requested ordering is established, otherwise `false`.
1888
+ * @throws {@link core!UnsupportedOperationError}
1889
+ * Thrown when either side is classified as complex.
1890
+ */
1891
+ lte(x) {
1892
+ x = Expression.create(x);
1893
+ return (0, compare_1.lte)(this, x);
1894
+ }
1895
+ /**
1896
+ * Subtracts `x` from this Expression.
1897
+ *
1898
+ * @param x - The value to subtract.
1899
+ * @returns A new Expression representing `this − x`.
1900
+ *
1901
+ * @example
1902
+ * ```ts
1903
+ * Expression.create('x').minus(1).text() // "-1+x"
1904
+ * Expression.create(10).minus(3).text() // "7"
1905
+ * ```
1906
+ */
1907
+ minus(x) {
1908
+ return (0, subtract_1.subtract)(this, Expression.create(x));
1909
+ }
1910
+ /**
1911
+ * Computes the modulo of this Expression by `x`.
1912
+ *
1913
+ * @param x - The divisor.
1914
+ * @returns A new Expression representing `this mod x`.
1915
+ *
1916
+ * @example
1917
+ * ```ts
1918
+ * Expression.create(10).mod(3).text() // "1"
1919
+ * ```
1920
+ */
1921
+ mod(x) {
1922
+ return (0, math_1.mod)(this, Expression.create(x));
1923
+ }
1924
+ /**
1925
+ * Legacy alias for {@link times}.
1926
+ *
1927
+ * @param x - The value to multiply by.
1928
+ * @returns A new Expression representing `this * x`.
1929
+ */
1930
+ multiply(x) {
1931
+ return this.times(x);
1932
+ }
1933
+ /**
1934
+ * Negates this Expression by flipping the sign of the multiplier.
1935
+ *
1936
+ * @returns A new Expression equal to `this * −1`.
1937
+ *
1938
+ * @example
1939
+ * ```ts
1940
+ * Expression.create(5).neg().text() // "-5"
1941
+ * Expression.create('x').neg().text() // "-x"
1942
+ * ```
1943
+ */
1944
+ neg() {
1945
+ const retval = this.copy();
1946
+ retval.multiplier = retval.getMultiplier().neg();
1947
+ return retval;
1948
+ }
1949
+ /**
1950
+ * Legacy alias for {@link getNumerator}.
1951
+ *
1952
+ * @returns The numerator Expression.
1953
+ */
1954
+ numerator() {
1955
+ return this.getNumerator();
1956
+ }
1957
+ /**
1958
+ * Compatibility alias for the copy-oriented base extraction used by
1959
+ * {@link Expression.toLinearAndUnitMultiplier}.
1960
+ *
1961
+ * @returns An independent Expression representing the node's mathematical base.
1962
+ */
1963
+ parseValue() {
1964
+ const retval = this.toLinearAndUnitMultiplier();
1965
+ return retval;
1966
+ }
1967
+ /**
1968
+ * Adds `x` to this Expression.
1969
+ *
1970
+ * @param x - The value to add.
1971
+ * @returns A new Expression representing `this + x`.
1972
+ *
1973
+ * @example
1974
+ * ```ts
1975
+ * Expression.create('x').plus(1).text() // "1+x"
1976
+ * Expression.create(2).plus(3).text() // "5"
1977
+ * ```
1978
+ */
1979
+ plus(x) {
1980
+ return (0, add_1.add)(this, Expression.create(x));
1981
+ }
1982
+ /**
1983
+ * Raises this expression to a symbolic or numeric exponent.
1984
+ *
1985
+ * @remarks
1986
+ * The operation delegates to Nerdamer's power canonicalization and simplification
1987
+ * rules. Noninteger and complex powers follow principal-branch semantics; identities
1988
+ * such as distributing a fractional power over arbitrary products are therefore
1989
+ * applied only when the implementation can preserve the relevant branch.
1990
+ *
1991
+ * The receiver is not modified.
1992
+ *
1993
+ * @param x - Exponent to apply.
1994
+ * @returns The simplified power expression.
1995
+ * @throws {@link core!UndefinedError}
1996
+ * Thrown for undefined infinity-related powers handled by the power operation.
1997
+ * @throws {@link core!ZeroToZeroPowerError}
1998
+ * Thrown for zero-power cases classified as undefined by the power operation.
1999
+ */
2000
+ pow(x) {
2001
+ return (0, power_1.power)(this, Expression.create(x));
2002
+ }
2003
+ /**
2004
+ * Returns Nerdamer's symbolic decomposition of the real component.
2005
+ *
2006
+ * @remarks
2007
+ * Decomposition follows principal-branch handling for powered complex values.
2008
+ * Explicitly complex function calls that cannot be decomposed are preserved through
2009
+ * a symbolic `realpart(...)` wrapper rather than being guessed. The component
2010
+ * functions `realpart(...)` and `imagpart(...)` are themselves treated as real-valued.
2011
+ *
2012
+ * @returns The symbolic real component.
2013
+ */
2014
+ realPart() {
2015
+ return (0, complex_1.realPart)(this);
2016
+ }
2017
+ /**
2018
+ * Returns the sign encoded by this node's coefficient representation.
2019
+ *
2020
+ * @remarks
2021
+ * This is not a general symbolic sign analysis. Most node types return the sign of
2022
+ * their outer {@link Rational} multiplier. `EXP` nodes additionally multiply that
2023
+ * result by the representation-level sign of their stored base. Unknown assumptions
2024
+ * are not inferred here.
2025
+ *
2026
+ * @returns `-1`, `0`, or `1` from the represented coefficient/base sign.
2027
+ */
2028
+ sign() {
2029
+ // REFACTOR:
2030
+ // Deal with numeric EXP
2031
+ if (this.type === EXP) {
2032
+ return this.getBase().sign() * this.getMultiplier().sign();
2033
+ }
2034
+ return this.getMultiplier().sign();
2035
+ }
2036
+ /**
2037
+ * Removes the sign represented by this expression's current form.
2038
+ *
2039
+ * @remarks
2040
+ * Complex expressions return their modulus `sqrt(re^2 + im^2)`. For other
2041
+ * expressions, the method copies the node and removes a negative stored sign or
2042
+ * multiplier. This is representation-oriented normalization, not a general
2043
+ * assumption-driven implementation of symbolic `abs(...)`.
2044
+ *
2045
+ * @returns A new sign-free expression or complex modulus.
2046
+ */
2047
+ signFree() {
2048
+ let retval;
2049
+ if (this.isComplex()) {
2050
+ retval = this.abs();
2051
+ }
2052
+ else {
2053
+ retval = this.copy();
2054
+ const m = retval.getMultiplier();
2055
+ // Remove the minus sign from retval value. This is specifically for EXP of numeric values
2056
+ if (retval.value.startsWith('-')) {
2057
+ retval.value = retval.value.substring(1);
2058
+ }
2059
+ if (m.lt('0')) {
2060
+ retval.multiplier = m.neg();
2061
+ }
2062
+ }
2063
+ return retval;
2064
+ }
2065
+ /**
2066
+ * Formats this expression using SymPy-style `**` exponentiation syntax.
2067
+ *
2068
+ * @remarks
2069
+ * Formatting temporarily switches the class-wide power-operator token while
2070
+ * delegating to the normal expression formatter, then restores `^`. The expression
2071
+ * itself is not modified.
2072
+ *
2073
+ * @param options - Formatting options accepted by the normal text formatter.
2074
+ * @param asId - Request the internal identifier-oriented formatting mode.
2075
+ * @returns SymPy-compatible expression text.
2076
+ */
2077
+ sptext(options, asId) {
2078
+ // Store the existing power operator
2079
+ const opr = Expression.POW_OPR;
2080
+ // Use the SymPy type
2081
+ Expression.POW_OPR = '**';
2082
+ const txt = (0, format_1.toText)(this, options, asId, Expression.POW_OPR, Expression.sortFunction);
2083
+ // Put back the original
2084
+ Expression.POW_OPR = opr;
2085
+ return txt;
2086
+ }
2087
+ /**
2088
+ * Squares this Expression. Shorthand for `this.pow('2')`.
2089
+ *
2090
+ * @returns A new Expression representing `this²`.
2091
+ *
2092
+ * @example
2093
+ * ```ts
2094
+ * Expression.create('x').sq().text() // "x^2"
2095
+ * Expression.create(5).sq().text() // "25"
2096
+ * ```
2097
+ */
2098
+ sq() {
2099
+ return this.pow('2');
2100
+ }
2101
+ /**
2102
+ * Tests Nerdamer equality while also requiring the same top-level internal type.
2103
+ *
2104
+ * @remarks
2105
+ * This is stricter than {@link Expression.eq}, but it is still not object identity or
2106
+ * byte-for-byte tree equality. After verifying matching top-level types (or matching
2107
+ * function names for function nodes), it delegates to Nerdamer's symbolic equality
2108
+ * comparison.
2109
+ *
2110
+ * @param x - Value to compare with this expression.
2111
+ * @returns `true` when the type/name requirement and symbolic equality both hold.
2112
+ */
2113
+ strictEqual(x) {
2114
+ x = Expression.create(x);
2115
+ const matchesExactly = x.isFunction() && this.isFunction() ? x.name === this.name : x.type === this.type;
2116
+ return matchesExactly && (0, compare_1.equal)(this, x);
2117
+ }
2118
+ /**
2119
+ * Legacy alias for {@link subst}.
2120
+ *
2121
+ * @param value - The sub-expression to find.
2122
+ * @param withValue - The replacement expression.
2123
+ * @returns A new Expression with the substitution applied.
2124
+ */
2125
+ sub(value, withValue) {
2126
+ return this.subst(value, withValue);
2127
+ }
2128
+ /**
2129
+ * Replaces occurrences of one symbolic expression with another.
2130
+ *
2131
+ * @remarks
2132
+ * Substitution supports more than direct variable replacement: the underlying
2133
+ * algorithm can match compatible products and sums, recurse into function arguments,
2134
+ * and substitute within powers. Inputs are converted through
2135
+ * {@link Expression.create}. The receiver is not mutated as part of normal execution. Unchanged
2136
+ * branches can preserve the receiver's identity, and an exact match can return the
2137
+ * supplied replacement object directly, so callers that require independent ownership
2138
+ * should copy the result explicitly.
2139
+ *
2140
+ * @param value - Symbolic value or sub-expression to match.
2141
+ * @param withValue - Replacement value.
2142
+ * @returns The expression produced by the substitution algorithm.
2143
+ */
2144
+ subst(value, withValue) {
2145
+ value = Expression.create(value);
2146
+ withValue = Expression.create(withValue);
2147
+ return (0, subst_1.subst)(this, value, withValue);
2148
+ // Based on the value:
2149
+ // If it's a number then complain. Invalid LH value
2150
+ // If it's a variable then return the multiplier times that value
2151
+ // If it's a function and the value is equal to that values within some multiplier the sub
2152
+ // otherwise call sub on the arguments.
2153
+ // If it's a sum then loop through each element and sub except for numbers
2154
+ // if a number is encountered and the difference is positive then sub it in and return the difference
2155
+ }
2156
+ /**
2157
+ * Legacy alias for {@link minus}.
2158
+ *
2159
+ * @param x - The value to subtract.
2160
+ * @returns A new Expression representing `this − x`.
2161
+ */
2162
+ subtract(x) {
2163
+ return this.minus(x);
2164
+ }
2165
+ /**
2166
+ * Formats this expression using Nerdamer's canonical text formatter.
2167
+ *
2168
+ * @remarks
2169
+ * Exact rational text is the default. Use `sort: true` to render terms in Nerdamer's
2170
+ * conventional display order without changing the stored expression. Decimal output,
2171
+ * precision, scientific notation, and power wrapping can also be selected per call. The `asId` mode is used
2172
+ * by internal identity/canonicalization logic and should not be
2173
+ * treated as a stable interchange format.
2174
+ *
2175
+ * @param options - Text-formatting options.
2176
+ * @param asId - Use the internal identifier-oriented formatting mode.
2177
+ * @returns The formatted expression text.
2178
+ *
2179
+ * @example
2180
+ * ```ts
2181
+ * Expression.create('x^2 + 2*x + 1').text(); // "1+2*x+x^2"
2182
+ * Expression.create('x^2 + 2*x + 1').text({ sort: true }); // "x^2+2*x+1"
2183
+ * Expression.create('1/3').text(); // "1/3"
2184
+ * Expression.create('1/3').text({ decimal: true }); // decimal representation
2185
+ * Expression.create('12345').text({ scientific: 3 }); // "1.23e4"
2186
+ * ```
2187
+ */
2188
+ text(options, asId) {
2189
+ if (options === undefined &&
2190
+ asId === undefined &&
2191
+ this.precision === undefined &&
2192
+ this.scientific === undefined) {
2193
+ return (0, format_1.toDefaultText)(this, Expression.POW_OPR, Expression.sortFunction);
2194
+ }
2195
+ return (0, format_1.toText)(this, options, asId, Expression.POW_OPR, Expression.sortFunction);
2196
+ }
2197
+ /**
2198
+ * Multiplies this Expression by `x`.
2199
+ *
2200
+ * @param x - The value to multiply by.
2201
+ * @returns A new Expression representing `this * x`.
2202
+ *
2203
+ * @example
2204
+ * ```ts
2205
+ * Expression.create('x').times(3).text() // "3*x"
2206
+ * Expression.create('x').times('y').text() // "x*y"
2207
+ * ```
2208
+ */
2209
+ times(x) {
2210
+ return (0, multiply_1.multiply)(this, Expression.create(x));
2211
+ }
2212
+ /**
2213
+ * Formats this expression using decimal numeric output.
2214
+ *
2215
+ * This is a formatting operation equivalent to calling {@link Expression.text} with
2216
+ * `{ decimal: true }`; it does not convert the expression tree into a floating-point
2217
+ * data structure.
2218
+ *
2219
+ * @param precision - Optional decimal formatting precision.
2220
+ * @returns Decimal-form expression text.
2221
+ */
2222
+ toDecimal(precision) {
2223
+ const options = { decimal: true };
2224
+ if (precision !== undefined) {
2225
+ options.precision = precision;
2226
+ }
2227
+ return this.text(options);
2228
+ }
2229
+ /**
2230
+ * Returns an independent base expression with the outer multiplier and power removed.
2231
+ *
2232
+ * @remarks
2233
+ * Base extraction is defined by {@link Expression.getBase}. Because `getBase()`
2234
+ * exposes an `EXP` node's stored base by reference, this method copies
2235
+ * that base before returning it. Non-`EXP` bases are already independent copies.
2236
+ *
2237
+ * @returns An independent expression representing the node without its outer multiplier and power.
2238
+ */
2239
+ toLinearAndUnitMultiplier() {
2240
+ let retval = this.getBase();
2241
+ if (this.isEXP()) {
2242
+ retval = retval.copy();
2243
+ }
2244
+ return retval;
2245
+ }
2246
+ // /**
2247
+ // * Converts the expression to a predictable (standard) string for easy matching with respect to a variable.
2248
+ // *
2249
+ // * @param variable
2250
+ // * @returns
2251
+ // */
2252
+ // toPattern(variable: string) {
2253
+ // return toPattern(this, variable);
2254
+ // }
2255
+ /**
2256
+ * Returns the string representation. Alias for {@link text}.
2257
+ *
2258
+ * @param options - Formatting options passed to {@link text}.
2259
+ * @returns The text representation.
2260
+ */
2261
+ toString(options) {
2262
+ return this.text(options);
2263
+ }
2264
+ /**
2265
+ * Returns the total degree of a monomial by summing the powers of all factors
2266
+ * in a product expression. For non-product types, returns the expression's own power.
2267
+ *
2268
+ * @returns The total power as an Expression.
2269
+ *
2270
+ * @example
2271
+ * ```ts
2272
+ * Expression.create('x^2*y^3').totalPower().text() // "5"
2273
+ * Expression.create('x^4').totalPower().text() // "4"
2274
+ * ```
2275
+ */
2276
+ totalPower() {
2277
+ if (!this.isProduct()) {
2278
+ return this.getPower();
2279
+ }
2280
+ let retval = Expression.Number('0');
2281
+ const elements = this.getElements();
2282
+ for (const x in elements) {
2283
+ retval = retval.plus(elements[x].getPower());
2284
+ }
2285
+ return retval;
2286
+ }
2287
+ /**
2288
+ * Returns a copy of this Expression with the multiplier removed (set to `1`).
2289
+ *
2290
+ * For `NUM` types (where the multiplier *is* the value), returns `1`.
2291
+ *
2292
+ * @returns A new multiplier-free Expression.
2293
+ *
2294
+ * @example
2295
+ * ```ts
2296
+ * Expression.create('3*x').toUnitMultiplier().text() // "x"
2297
+ * Expression.create(5).toUnitMultiplier().text() // "1"
2298
+ * ```
2299
+ */
2300
+ toUnitMultiplier() {
2301
+ let retval;
2302
+ if (this.isNUM()) {
2303
+ // Since type NUM carries its value in the multiplier,
2304
+ // the remainder is just one
2305
+ retval = (0, shortcuts_1.one)();
2306
+ }
2307
+ else {
2308
+ retval = this.copy();
2309
+ delete retval.multiplier;
2310
+ }
2311
+ return retval;
2312
+ }
2313
+ /**
2314
+ * Regenerates the stored `value` string from mutable structural state where supported.
2315
+ *
2316
+ * @remarks
2317
+ * Function nodes rebuild `value` from their name and arguments. Product and sum-like
2318
+ * nodes rebuild it from their current elements. Other node types are left unchanged.
2319
+ * This method mutates the receiver and returns the same object for chaining.
2320
+ *
2321
+ * @param aggregateElements - Exact aggregate elements already available to a caller
2322
+ * rebuilding a SUM/PRD node. When supplied, the generated value is also the ordinary
2323
+ * lookup key and can seed the key cache without a second formatting pass.
2324
+ * @returns This expression after updating its stored value where applicable.
2325
+ */
2326
+ updateValue(aggregateElements) {
2327
+ this._keyValueCache = undefined;
2328
+ if (this.isFunction()) {
2329
+ this.value = `${this.name}(${this.getArguments()
2330
+ .map(x => x.text())
2331
+ .join(', ')})`;
2332
+ }
2333
+ else if (this.isProduct() || this.isSum()) {
2334
+ const elements = aggregateElements ?? this.elementsArray();
2335
+ this.value = Expression.getValue(elements, 'text', this.type);
2336
+ if (aggregateElements && (this.type === SUM || this.type === PRD)) {
2337
+ this._keyValueCache = this.value;
2338
+ }
2339
+ }
2340
+ return this;
2341
+ }
2342
+ /**
2343
+ * Provides the primitive value used by JavaScript coercion.
2344
+ *
2345
+ * Numeric (`NUM`) expressions return the primitive value of their rational
2346
+ * multiplier. Other expressions return decimal-formatted text. This coercion API is
2347
+ * intended for JavaScript interoperability; use explicit symbolic comparison methods
2348
+ * when mathematical equality or ordering is required.
2349
+ *
2350
+ * @returns A number for numeric nodes, otherwise decimal-form expression text.
2351
+ */
2352
+ valueOf() {
2353
+ let retval;
2354
+ if (this.isNUM()) {
2355
+ retval = this.getMultiplier().valueOf();
2356
+ }
2357
+ else {
2358
+ retval = this.text({ decimal: true });
2359
+ }
2360
+ return retval;
2361
+ }
2362
+ /**
2363
+ * Collects distinct free-variable names from this expression tree.
2364
+ *
2365
+ * @remarks
2366
+ * Only `VAR` nodes are collected. The current imaginary-unit symbol and names in
2367
+ * {@link Expression.RESERVED} are excluded. Traversal includes function arguments,
2368
+ * aggregate elements, and `EXP` bases and powers. Encounter order is preserved unless
2369
+ * the caller sorts the returned array separately.
2370
+ *
2371
+ * If `vars` is supplied, new names are appended to that same accumulator without
2372
+ * duplicating names already present.
2373
+ *
2374
+ * @param vars - Optional accumulator of names already collected.
2375
+ * @returns The accumulator containing distinct variable names.
2376
+ */
2377
+ variables(vars) {
2378
+ return (0, traversal_2.variables)(this, vars, Expression.RESERVED);
2379
+ }
2380
+ }
2381
+ exports.Expression = Expression;