Published
Edited
Apr 22, 2020
Insert cell
md`# expr-eval`
Insert cell
parser = {
const parser = new (await require('expr-eval')).Parser();
const isDate = d => d instanceof Date && !isNaN(d);
// add a few useful functions for date objects
parser.functions.year = d => (isDate(d) ? d.getFullYear() : null);
parser.functions.month = d => (isDate(d) ? d.getMonth() + 1 : null);
parser.functions.day = d => (isDate(d) ? d.getDate() : null);
return parser;
}
Insert cell
evaluate = s => {
const expr = parser.parse(s);
return rows.map(row => expr.evaluate(row));
}
Insert cell
rows = [
{
foo: 1,
bar: 2,
label: 'Label A',
alt: 'Label AAAA',
date: new Date(2019, 0, 1)
},
{
foo: 10,
bar: 4,
label: 'Second row',
alt: 'Second rowwww',
date: new Date(2012, 0, 1)
}
]
Insert cell
evaluate('foo * bar')
Insert cell
evaluate('if(foo < 5,label,alt)')
Insert cell
evaluate('if(foo < 5,"small", "large")')
Insert cell
evaluate('foo < 5 ? "small" : label')
Insert cell
evaluate('random(100)')
Insert cell
evaluate('max(foo, bar)')
Insert cell
evaluate('year(foo)')
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