@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
89 lines (77 loc) • 2.25 kB
JavaScript
import { assert } from "../../../core/assert.js";
import { RingBufferMetric } from "./RingBufferMetric.js";
/**
* A class for managing a collection of metrics where each metric can store data and be accessed by name.
* Provides functionality to add, retrieve, list, and clear metrics.
*
* @example
* const metrics = new MetricCollection();
* metrics.create({name: "execution time"});
*
* // ... record metrics
* const t0 = performance.now();
* do_expensive_computation();
* const t1 = performance.now();
*
* metrics.get("execution time").record(t1 - t0);
*
* // ... read stats
* const stats = metrics.get("execution time").stats;
*
* console.log(`Average execution time: ${stats.mean}`);
*/
export class MetricCollection {
/**
* @private
* @type {Map<string, AbstractMetric>}
*/
data = new Map();
/**
* Clear all data records.
* Note: does not remove any metrics, just the data within them
*/
clear() {
this.data.forEach((value, key) => {
value.clear();
});
}
/**
* Get names of available metrics
* @returns {string[]}
*/
list() {
return Array.from(this.data.keys());
}
/**
*
* @param {string} name
* @param {number} [buffer_size] The larger this number is - the more detail metric can hold. If you plan to compute statistics, this is your sample size.
* @returns {AbstractMetric}
*/
create({ name, buffer_size = 128 }) {
const metric = new RingBufferMetric(buffer_size);
this.add(name, metric);
return metric;
}
/**
*
* @param {string} name
* @param {AbstractMetric} metric
*/
add(name, metric) {
assert.isString(name, 'name');
assert.defined(metric, 'metric');
assert.isObject(metric, "metric");
assert.equal(metric.isMetric, true, "metric");
this.data.set(name, metric);
}
/**
*
* @param {string} name
* @returns {AbstractMetric|undefined}
*/
get(name) {
assert.isString(name, 'name');
return this.data.get(name);
}
}