Open in a new tab

Mean, median, standard deviation and a histogram of a number list, and the value at a position t between its extremes, linear and eased.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Dashboards, charts and gauges need small numeric helpers: descriptive statistics for a series, and interpolation to place a marker or animate a value between two ends, without pulling a numeric library.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • stats.mean / median / stddev (population by default) / min / max and stats.histogram(values, bins) returning edges and counts; the last bin includes the maximum.
  • interp.linear(a, b, t), and the same move eased by interp.smoothstep(0, 1, t): move the slider to see the two curves differ everywhere except at the ends and in the middle.
  • Input parsing that reports the offending token rather than printing NaN.

Code

main.js

javascriptApache-2.076 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { stats } from '@awacloud/fw/io/math/stats.js';
import { interp } from '@awacloud/fw/io/math/interp.js';

fw.runtime.registerAllDeep([stats, interp]);
const STATS = fw.runtime.resolve('stats');
const INTERP = fw.runtime.resolve('interp');

/** The histogram's number of bins. */
const BINS = 3;
/** @param {number} n */
const round = (n) => Math.round(n * 1000) / 1000;

/**
 * @param {string} text comma-separated numbers
 * @returns {number[]}
 * @throws {Error} when a token is not a finite number
 */
export function parseNumbers(text) {
    return text.split(',').map((s) => s.trim()).filter(Boolean).map((s) => {
        const n = Number(s);
        if (!Number.isFinite(n)) throw new Error(`"${s}" is not a number`);
        return n;
    });
}

/**
 * Describe a list, and the value at `t` between its extremes, straight and eased.
 * @param {number[]} values at least one
 * @param {number} t between 0 and 1
 */
export function summarize(values, t) {
    const min = STATS.min(values);
    const max = STATS.max(values);
    return {
        mean: round(STATS.mean(values)),
        median: STATS.median(values),
        stddev: round(STATS.stddev(values)),
        histogram: STATS.histogram(values, BINS),
        linear: round(INTERP.linear(min, max, t)),
        eased: round(INTERP.linear(min, max, INTERP.smoothstep(0, 1, t))),
    };
}

/** @param {{ edges: number[], counts: number[] }} histogram */
function binsText({ edges, counts }) {
    return counts.map((count, i) => {
        const close = i === counts.length - 1 ? ']' : ')'; // the last bin includes the maximum
        return `[${round(edges[i])}, ${round(edges[i + 1])}${close}: ${count}`;
    }).join('  ');
}

/** @param {string} id */
const field = (id) => /** @type {HTMLInputElement} */ (document.getElementById(id));
/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };

function update() {
    try {
        const values = parseNumbers(field('numbers').value);
        if (values.length === 0) throw new Error('enter at least one number');
        const t = Number(field('t').value);
        const s = summarize(values, t);
        show('error', '');
        show('summary', `${s.mean} / ${s.median} / ${s.stddev}`);
        show('histogram', binsText(s.histogram));
        show('interp', `at t = ${t}: linear ${s.linear}, eased ${s.eased}`);
    } catch (err) {
        show('error', /** @type {Error} */ (err).message);
    }
}

field('numbers').addEventListener('input', update);
field('t').addEventListener('input', update);
update();

index.html

htmlApache-2.030 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Describe a list of numbers</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Describe a list of numbers</h1>
    <label for="numbers">Numbers (comma-separated)</label>
    <input id="numbers" type="text" value="3, 1, 4, 1, 5, 9, 2, 6" autocomplete="off">
    <p id="error" class="error" aria-live="polite"></p>
    <dl>
      <dt>Mean / median / standard deviation</dt><dd><output id="summary"></output></dd>
      <dt>Histogram (3 bins)</dt><dd><output id="histogram"></output></dd>
    </dl>
    <label for="t">Position <var>t</var> between the minimum and the maximum</label>
    <input id="t" type="range" min="0" max="1" step="0.05" value="0.25">
    <p><output id="interp" for="numbers t"></output></p>
  </main>
</body>
</html>