Skip to content

Instantly share code, notes, and snippets.

@humphd
Last active November 3, 2024 23:00
Show Gist options
  • Save humphd/b75094165cbe3bc8a994a1b3d6cc9ede to your computer and use it in GitHub Desktop.
Save humphd/b75094165cbe3bc8a994a1b3d6cc9ede to your computer and use it in GitHub Desktop.
Evaluate a mathjs expression and return the result
/**
* Evaluates a mathjs expression and returns the result
* @param expr A Math.js (https://mathjs.org/) compatible exression string
* @returns A Promise that resolves to the result of the math expression
*/
export async function evaluateMathExpressionWithMathJs(expr: string): Promise<number> {
/**
* Loads the Math.js library dynamically and returns a promise
* that resolves when the library is loaded. Currently not possible
* to load as ESM, see https://github.com/josdejong/mathjs/issues/1841
*/
function loadMathJs(): Promise<void> {
return new Promise((resolve, reject) => {
if (window.math) {
resolve();
return;
}
const script = document.createElement('script');
script.src =
'https://cdn.jsdelivr.net/npm/[email protected]/lib/browser/math.min.js';
script.onload = () => {
window.math = math;
resolve();
};
script.onerror = () => {
reject(new Error('Failed to load Math.js library'));
};
document.head.appendChild(script);
});
}
try {
await loadMathJs();
return math.evaluate(expr);
} catch(err) {
throw new Error(`Unable to evaluate expression "${expr}" with mathjs: ${err.message}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment