DEV Community

USA Beam
USA Beam

Posted on

Running 14 math solvers in the browser with Astro, no backend

 Math Questions Hub is a static Astro site with solvers for 14 math topics. There's no server, and every answer is calculated in the browser.

This post covers the pattern the solvers follow, and what it does for testing and sharing.

Each solver is a pure function

A solver takes an input and returns a result. It doesn't read the page, call an API, or keep state.

Here's a simplified example of that pattern, a quadratic solver written for this post. It isn't the code from the site.

type Result =
  | { ok: true; roots: number[] }
  | { ok: false; error: string };

export function solveQuadratic(a: number, b: number, c: number): Result {
  if (![a, b, c].every(Number.isFinite)) {
    return { ok: false, error: "Inputs must be numbers" };
  }
  if (a === 0) {
    return { ok: false, error: "a can't be 0 in a quadratic" };
  }

  const d = b * b - 4 * a * c;
  if (d < 0) return { ok: true, roots: [] };
  if (d === 0) return { ok: true, roots: [-b / (2 * a)] };

  const s = Math.sqrt(d);
  return { ok: true, roots: [(-b - s) / (2 * a), (-b + s) / (2 * a)] };
}
Enter fullscreen mode Exit fullscreen mode

The same input always gives the same output, so each solver can be tested with a table of known problems and answers.

Invalid input returns a result

The function returns an error object for bad input instead of throwing. The interface can show the message next to the field without a try/catch around every call.

Every question has its own link

A student can send a problem to a teacher or classmate, and it opens the same result. That works because the link only needs to carry the input.

Guides sit beside the solvers

Each topic has a long-form guide explaining the method. The solver gives the answer, and the guide lets a student check their own working against it.

Why static

There's no server to run, and nothing to scale when traffic spikes. Pages load fast, since a calculator doesn't wait for a network call. Calculations run in the browser.

Try it at https://mathquestionshub.com/

Which topic should come next? If a solver returns a result that looks wrong, post the problem in the comments and it will be checked.

Top comments (0)