Replacing a JS library

I’ve written v 1.0.0 of a library in JS. The main exports are some function for creating and manipulating a certain domain-specific data type. I really want to rewrite v 2.0.0 in a typed language. Is there a pattern for writing it in Elm and exposing some functions to JS or TS? I’m really struggling to see how to use ports and message-passing here.

It’s difficult to give you any specific guidance without a little more context. Perhaps you could give us an example of one of your exposed functions and some expectations of what you think an Elm version could/should do?

I don’t think you will have much fun with that approach, at least not for a loose collection of functions. You’ll basically ship the whole elm runtime and have to add an adapter for your API to consume from the JS side. The gist would look something like this if I’d be trying to do this:

(function (window) {

import { Elm } from './lib.js'; // import built Elm stuff somehow

// If you need to configure the library you'll have to expose a factory
// otherwise it'll be ok to just expose the api
const factory = (flags) => {

    const lib = Elm.Main.init({
        flags: flags,

    lib.ports.someFunctionResult.subscribe((value) => {
        // Somehow figure out how to match this output to the
        // corresponding input
    // Callback or Promise?
    const someAsyncFunction = (data) => {
        return new Promise((resolve, reject) => {
            // Somehow match this input to the corresponding output
            // ...
            // When this result is ready return the result

    // Your API
    return {

// UMD or something in that vein
window['YourLibFactory'] = factory;


const lib = YourLibFactory({ /* flags */ });
const value = await lib.someAsyncFunction(42);

That should work although I’m not sure how well it’d turn out in a real life setting.

Thanks for the replies. I think it’s looking like PureScript is going to be a better candidate for this (PS functions are exposed in JS as curried but otherwise normal-looking functions).

For the interested, the original library generates probability grids using Poisson or bivariate Poisson distributions, then has functions for downsampling, aggregating, and combining those grids. It’s all very mathematical.

1 Like

If it’s all numbers, wouldn’t make sense to use something like Rust and compile it to webasm?


Oh, now that’s interesting. Yeah, I’ll look into it.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.