squiggle/packages/squiggle-lang/scripts/lib.mjs

42 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2022-09-19 20:55:32 +00:00
import { SqProject } from "@quri/squiggle-lang";
export const measure = (cb, times = 1) => {
const t1 = new Date();
for (let i = 1; i <= times; i++) {
cb();
}
const t2 = new Date();
return (t2 - t1) / 1000;
};
export const red = (str) => `\x1b[31m${str}\x1b[0m`;
export const green = (str) => `\x1b[32m${str}\x1b[0m`;
2022-09-20 16:54:26 +00:00
export const run = (src, { output, sampleCount } = {}) => {
2022-09-19 20:55:32 +00:00
const project = SqProject.create();
if (sampleCount) {
project.setEnvironment({
sampleCount: Number(sampleCount),
xyPointLength: Number(sampleCount),
});
}
project.setSource("main", src);
const time = measure(() => project.run("main"));
const bindings = project.getBindings("main");
const result = project.getResult("main");
if (output) {
console.log("Result:", result.tag, result.value.toString());
console.log("Bindings:", bindings.toString());
}
console.log(
"Time:",
String(time),
result.tag === "Error" ? red(result.tag) : green(result.tag),
2022-10-05 11:49:16 +00:00
result.tag === "Error" ? result.value.toStringWithFrameStack() : ""
2022-09-19 20:55:32 +00:00
);
};