benchmark-suite
Version:
A simple suite of benchmarking tests
55 lines (54 loc) • 1.92 kB
JavaScript
import EventEmitter from 'eventemitter3';
import Memory from './MemoryTest.js';
import Operations from './OperationsTest.js';
export { default as MemoryTest } from './MemoryTest.js';
export { default as OperationsTest } from './OperationsTest.js';
export * from './types.js';
const TESTS = {
Memory: Memory,
Operations: Operations
};
const toJSON = (results)=>{
const json = {};
for(const key in results){
json[key] = {
name: results[key].name
};
json[key].stats = results[key].stats.toJSON();
}
return json;
};
const isString = (x)=>Object.prototype.toString.call(x) === '[object String]';
let Suite = class Suite extends EventEmitter {
add(name, fn) {
this.tests.push(new this.TestClass(name, fn));
}
async run(options = {}) {
if (!options.time) throw new Error('Missing time option');
const results = {};
for (const test of this.tests){
const result = await test.run(options);
for(const key in result){
if (!results[key] || test.metric(results[key].stats) < test.metric(result[key].stats)) results[key] = result[key];
}
this.emit('cycle', toJSON(result));
}
this.emit('complete', toJSON(results));
return results;
}
formatStats(stats) {
if (!this.tests.length) throw new Error('Add tests before calling formatStats');
return this.tests[0].formatStats(stats);
}
constructor(name, testOrType){
super();
this.name = name;
if (!testOrType) throw new Error('Suite needs a test');
if (isString(testOrType)) {
this.TestClass = TESTS[testOrType];
if (!this.TestClass) throw new Error(`Suite test type not recognized ${testOrType}`);
} else this.TestClass = testOrType;
this.tests = [];
}
};
export { Suite as default };