diff --git a/packages/components/src/index.ts b/packages/components/src/index.ts index ffd9c8e0..a35b28bb 100644 --- a/packages/components/src/index.ts +++ b/packages/components/src/index.ts @@ -9,3 +9,5 @@ import SquigglePlayground, { renderSquigglePlaygroundToDom, } from "./components/SquigglePlayground"; export { SquigglePlayground, renderSquigglePlaygroundToDom }; + +export { mergeBindings } from "@quri/squiggle-lang"; diff --git a/packages/squiggle-lang/__tests__/TS/JS_test.ts b/packages/squiggle-lang/__tests__/TS/JS_test.ts index 76871fc8..8d2d5a1c 100644 --- a/packages/squiggle-lang/__tests__/TS/JS_test.ts +++ b/packages/squiggle-lang/__tests__/TS/JS_test.ts @@ -1,4 +1,9 @@ -import { Distribution, resultMap, defaultBindings } from "../../src/js/index"; +import { + Distribution, + resultMap, + defaultBindings, + mergeBindings, +} from "../../src/js/index"; import { testRun, testRunPartial } from "./TestHelpers"; function Ok(x: b) { @@ -66,6 +71,17 @@ describe("Partials", () => { value: 10, }); }); + test("Can merge bindings from three partials", () => { + let bindings1 = testRunPartial(`x = 1`); + let bindings2 = testRunPartial(`y = 2`); + let bindings3 = testRunPartial(`z = 3`); + expect( + testRun(`x + y + z`, mergeBindings([bindings1, bindings2, bindings3])) + ).toEqual({ + tag: "number", + value: 6, + }); + }); }); describe("JS Imports", () => { diff --git a/packages/squiggle-lang/src/js/index.ts b/packages/squiggle-lang/src/js/index.ts index 589548e3..961d4935 100644 --- a/packages/squiggle-lang/src/js/index.ts +++ b/packages/squiggle-lang/src/js/index.ts @@ -48,7 +48,7 @@ export function run( let i = imports ? imports : defaultImports; let e = environment ? environment : defaultEnvironment; let res: result = evaluateUsingOptions( - { externalBindings: mergeImports(b, i), environment: e }, + { externalBindings: mergeImportsWithBindings(b, i), environment: e }, squiggleString ); return resultMap(res, (x) => createTsExport(x, e)); @@ -67,12 +67,12 @@ export function runPartial( return evaluatePartialUsingExternalBindings( squiggleString, - mergeImports(b, i), + mergeImportsWithBindings(b, i), e ); } -function mergeImports( +function mergeImportsWithBindings( bindings: externalBindings, imports: jsImports ): externalBindings { @@ -90,6 +90,12 @@ type jsImports = { [key: string]: jsValue }; export let defaultImports: jsImports = {}; export let defaultBindings: externalBindings = {}; +export function mergeBindings( + allBindings: externalBindings[] +): externalBindings { + return allBindings.reduce((acc, x) => ({ ...acc, ...x })); +} + function createTsExport( x: expressionValue, environment: environment