Published
Edited
Dec 13, 2018
2 forks
Importers
14 stars
Insert cell
Insert cell
Insert cell
Insert cell
math`1+sqrt(2)`
Insert cell
A = math`[5,4,3,2,1]`
Insert cell
math` ${A}*${A}' `
Insert cell
math`
A = [1,2,3]
B = [4,5,6]
A*B'
`
Insert cell
math`
x = 3 + 4i
y = -1 + 0.5i
`
Insert cell
{
const vector = [6,5,4]
return math`${vector} + [1,1,1]`
}
Insert cell
Insert cell
Insert cell
function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
Insert cell
Insert cell
Insert cell
Insert cell
{
function example(strings, ...values) {
return {strings, values}
}
return example`start a=${a} b=${b} end`
}
Insert cell
Insert cell
function math(strings, ...values) {
let parser = mathjs.parser()
let text = ""
// text = strings[0] + "_value0" + strings[1] + "_value1" + ...
for (let [i,x] of values.entries()) {
parser.set("_value" + i, x)
text += strings[i] + "_value" + i
}
text += strings[strings.length - 1]
const ans = parser.eval(text)
let variables = parser.getAll()
let originalNames = Object.keys(variables).filter(x => x.indexOf("_value") !== 0)
//return {ans, variables, originalNames}

if (originalNames.length == 0) {
return ans // no variables used
} else {
const lastName = originalNames[originalNames.length - 1]
const lastAnswer = ans.entries[ans.entries.length - 1]
if (variables[lastName] !== lastAnswer) {
return lastAnswer
} else {
return originalNames.reduce((r,x) => { r[x] = variables[x]; return r }, {}) // return all variables
}
}
}
Insert cell
mathjs = require("https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.4.0/math.js")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more