Creating a Typescript Library that Relies on Web Assembly?

I'm considering developing a TypeScript library for distributions that will rely on cephes.

To enable the use of web assembly in browsers, we need to compile it in the following way:

const cephes = require('cephes'); // Browser
await cephes.compiled;

I'm unsure about how to implement this for a Typescript library that wraps cephes.

For instance, the library will provide a NormalDistribution that can be imported like this:

import { NormalDistrbution } from 'cephesdistributions';

If tree shaking is performed, NormalDistribution may be the only import included from the package. Should we then include await cephes.compiled in all modules offered by cephesdistributions?

Answer №1

It is important to be direct and clear with your approach when it comes to handling asynchronous operations in your code. One suggestion is to let consumers handle the await for `cephes.compiled` themselves.

If you are packaging `cephes`, consider exporting `cephes.compiled` so that users of your library can easily access it:

const cephes = require('cephes');

export const compiled = cephes.compiled;

export class NormalDistribution {
  public mean: number;
  public sd: number;

  constructor(mean = 0, sd = 1) {
    this.mean = mean;
    this.sd = 1;
  }

  cdf(x: number): number {
    // Make sure 'compiled' has been awaited before calling
    return cephes.ndtr(x);
  }
}

This way, the types of your exported classes will be readily available, even though they rely on `cephes.compiled`. To ensure proper handling of dependencies, you could track the compilation state and include appropriate guard clauses:

const cephes = require('cephes');
  
let isCompiled = false;
export function assertIsCompiled() {
  if (isCompiled) {
    return;
  }

  throw new Error('Please wait for `cephesdistributions.compiled` to resolve');
}

export const compiled = cephes.compiled.then(() => { isCompiled = true });

export class NormalDistribution {
  public mean: number;
  public sd: number;

  constructor(mean = 0, sd = 1) {
    assertIsCompiled();

    this.mean = mean;
    this.sd = 1;
  }

  cdf(x: number): number {
    return cephes.ndtr(x);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it feasible to retrieve information within a behavior in Drupal?

I recently installed the "Autologout" Drupal module, which can be found at . This module includes a timer that ends your session if there is no activity on the page for a set period of time. However, I am interested in adjusting the timer value to better ...

Having trouble extracting data from a particular cell within an HTML table using jQuery

I am struggling to extract row data from a table for utilization in a modal. Provided below is my code for Views. <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css"> <link href="@Url.Content(" ...

Sharing various data from Express to Jade is quite simple and can be done

I have a series of variables that are checking against a condition to determine if they return true or false. While I've been able to print these results using console.log, I now need to display them in a jade template. However, I'm encountering ...

Inject the JSON data fetched through AJAX into Datatables

I have been successfully using the datatables plugin to populate multiple tables with data. However, I realized that instead of making separate AJAX calls for each table, I could optimize by fetching the data once and storing it in a variable to be used by ...

Obtaining JSON Data Using WinJS.xhr():

I'm encountering difficulties with retrieving chat messages using winjs.xhr: function getMessage() { var time = MESSAGE_RETURNED.unixtime; if (time == 0) { time= window.parent.SESSION.unixtime; } WinJS.x ...

Tips for exporting data to a JSON file using the Google Play Scraper in NodeJS

Recently, I've been exploring the Google Play Scraper and I'm in need of a complete list of all appIds using NodeJS. The issue I'm facing is that it only outputs to console.log. What I really require is to save this output to JSON and then c ...

Use checkboxes to switch specific divs on and off based on their two assigned classes

Hey, I'm trying to implement some code with a specific structure: Initially, a main div is opened and checkboxes are created using a foreach loop. A checkbox is generated for each 'model' in an array. <div id='coltext'> & ...

Performing a map or foreach function on an array of objects limited to the first 5 objects

I need to iterate through an array of objects, but I only want to loop through the first 5 objects and then stop. What is the most efficient way to achieve this? [ {"visibility": 10000,}, {"visibility": 10000,}, {"visibilit ...

Creating a dynamic search bar using Ajax with support for multiple keywords

I recently attempted to create an ajax search bar for my website. It functions perfectly with a single keyword, however, I'm facing some difficulty when trying to make it work with two keywords. I thought about parsing the data in the input field, but ...

Searching for a specific value in various Json files: A guide

My goal is to create an application where users can input longitude and latitude coordinates of a location, and the application will return the associated grid code from one of three JSON data files. I am attempting to search through all three files simult ...

Enabling individuals to transfer their content to Amazon S3

I have set up an S3 bucket named BUCKET in region BUCKET_REGION. I want to enable users of my web and mobile apps to upload image files to this bucket, with specific restrictions based on Content-Type and Content-Length (specifically, only allowing jpegs u ...

Is Ember CLI experiencing issues due to the latest Ember Data update?

Greetings! I am a beginner with Ember and recently encountered some warnings after upgrading to the latest version of Ember Data: Update: I have two identical versions of my app, one built without ember-cli and the other with ember cli. Both applications ...

Conceal a specific character within a jQuery input field

I'm struggling to remove a dollar sign from an input field that is being filled with values from buttons. Even though the button populates the field, the dollar sign remains visible for some reason. Any assistance would be greatly appreciated. Thank ...

Using d3.xml() within a React application

Is it possible to use the d3.xml() method in a React application? I tried using the code below, but the debugger seems unable to access the function: d3.xml("http://upload.wikimedia.org/wikipedia/commons/a/a0/Circle__black_simple.svg", function(error, do ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

The style of the button label does not persist when onChange occurs

Encountered an interesting issue here. There is a button designed for selection purposes, similar to a select item. Here's the code snippet: <button class="btn btn-primary dropdown-toggle" style="width: 166%;" type="button" id="dropdownMe ...

Utilize the reducer from another slice in Redux Toolkit

I am working with an authSlice const authSlice = createSlice({ name: 'authStore', initialState, reducers: { logout(state = initialState) { return { ...state, isAuthenticated: false }; }, }, extraReducers: (builder) => { ...

Guide to modifying CSS properties of an individual element by manipulating class names with JavaScript

I have been searching for an answer to my question without success. I have a unique challenge where I need to change the styles of an h1 element by adding a class based on which radio button is clicked. The issue I'm facing is that when I select a dif ...

Utilizing Jquery to extract a specific string from a URL and fetch a remote element

Recently delving into Jquery, I'm in search of a code snippet that can capture the current page URL and load a remote element if it contains a specific string. For instance: Consider these sample page URLs: "http://......./Country/AU/result-search- ...