Skip to content

Instantly share code, notes, and snippets.

@GHolk
Created November 25, 2018 04:21
Show Gist options
  • Save GHolk/de01600aed974d2e9a61960a0b029d25 to your computer and use it in GitHub Desktop.
Save GHolk/de01600aed974d2e9a61960a0b029d25 to your computer and use it in GitHub Desktop.
this is a extension for mathjs, which allow you directly embed mathjs type variable in es6 tag template string.
/*
# mathjs es6 style tag template string
this is a extension for mathjs,
which allow you directly embed
mathjs type variable in es6 tag template string,
instead of pass variable by a dictionary object.
## usage
this script is useing commonjs style, use exports.
```
const m = MathJs.matrix([[1,2,3], [4,5,6]])
const mxm = MathJs.evalTag`m' * m`
```
### commonjs, nodejs style import
```
const libMathJsEvalTag = require('./mathjs-eval-tag.js')
MathJs.import(libMathJsEvalTag)
```
### in browser
```
<script src="./mathjs-eval-tag.js"></script>
<script>
MathJs.import({evalTag})
</script>
```
## origin mathjs eval
in origin mathjs eval,
you can use variable in math expression.
however if you want to pass variable inside,
ether write it literal, or pass it by a scope object
store variable name as key and value as object value.
```
const leastSquareSolution = MathJs.eval(`A' P A A' P L`, {
A: designMatrix,
L: observationVector,
P: weightMatrix
})
```
## es6 style tag template evalTag
in es6 tag template, you can customize behavor
of template string by define tag.
in other way, it allow you to customize
how to deal with the variable embed in the template string,
and the return value.
```
const leastSquareSolution = MathJs.evalTag`
${designMatrix}' ${weightMatrix} ${designMatrix} *
${designMatrix}' ${weightMatrix} ${observationVector}
`
```
*/
function evalTag (template, ...variable) {
const prefix = '_eval_tag_variable_'
const scope = {}
let expression = ''
for (let i=0; i<template.length; i++) {
if (i == 0) expression += template[i]
else {
const variableCount = i - 1
const variableName = prefix + variableCount
scope[variableName] = variable[variableCount]
expression += variableName + template[i]
}
}
// this == MathJs
return this.eval(expression, scope)
}
if (typeof exports == 'object') {
exports.evalTag = evalTag
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment