UNPKG

mathsteps-experimental-fork

Version:

Step by step math solutions. Experimental Fork

27 lines (24 loc) 1.34 kB
import { myNodeToString } from './myNodeToString.js'; import { flattenAndIndexTrackAST, termToString } from './nodeHelpers.js'; import { parseText } from './parseText.js'; function _tryParseTextTermToString(terms) { const cleanStrFn = (str) => str.replace(/\s+/g, "").replace(/\+\-/g, "-").replace(/\-\+/g, "-").replace(/\-\-/g, "+").replace(/\+\+/g, "+"); const stringTerm = termToString(terms); try { return parseText(cleanStrFn(stringTerm)); } catch (e) { console.log("error in tryTermToString", { stringTerm, terms, e }); return null; } } function removeUnnecessaryParentheses(expression) { const node = typeof expression === "string" ? parseText(expression) : expression; const expressionAsString = typeof expression === "string" ? expression : myNodeToString(node); const functions = ["sqrt", "log", "ln", "sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "atan", "acot", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "sech", "csch", "asinh", "acosh", "atanh", "acoth", "asech", "acsch"]; if (functions.some((f) => expressionAsString.toLowerCase().includes(f))) return node; const terms = flattenAndIndexTrackAST(node).sort((a, b) => a.index - b.index); const newNode = _tryParseTextTermToString(terms); return !newNode ? node : newNode; } export { removeUnnecessaryParentheses };