UNPKG

cmpstr

Version:

CmpStr is a lightweight, fast and well performing package for calculating string similarity

82 lines (80 loc) 2.27 kB
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License class Profiler { active; static ENV; static instance; nowFn; memFn; store = new Set(); totalTime = 0; totalMem = 0; static detectEnv() { if (typeof process !== 'undefined') Profiler.ENV = 'nodejs'; else if (typeof performance !== 'undefined') Profiler.ENV = 'browser'; else Profiler.ENV = 'unknown'; } static getInstance(enable) { if (!Profiler.ENV) Profiler.detectEnv(); return (Profiler.instance ||= new Profiler(enable)); } constructor(active = false) { this.active = active; switch (Profiler.ENV) { case 'nodejs': this.nowFn = () => Number(process.hrtime.bigint()) / 1e6; this.memFn = () => process.memoryUsage().heapUsed; break; case 'browser': this.nowFn = () => performance.now(); this.memFn = () => performance.memory?.usedJSHeapSize ?? 0; break; default: this.nowFn = () => Date.now(); this.memFn = () => 0; break; } } now = () => this.nowFn(); mem = () => this.memFn(); profile(fn, meta) { const startTime = this.now(), startMem = this.mem(); const res = fn(); const deltaTime = this.now() - startTime, deltaMem = this.mem() - startMem; this.store.add({ time: deltaTime, mem: deltaMem, res, meta }); ((this.totalTime += deltaTime), (this.totalMem += deltaMem)); return res; } enable = () => { this.active = true; }; disable = () => { this.active = false; }; clear() { this.store.clear(); this.totalTime = 0; this.totalMem = 0; } run(fn, meta = {}) { return this.active ? this.profile(fn, meta) : fn(); } async runAsync(fn, meta = {}) { return this.active ? this.profile(async () => await fn(), meta) : await fn(); } getAll = () => [...this.store]; getLast = () => this.getAll().pop(); getTotal = () => ({ time: this.totalTime, mem: this.totalMem }); services = Object.freeze({ enable: this.enable.bind(this), disable: this.disable.bind(this), clear: this.clear.bind(this), report: this.getAll.bind(this), last: this.getLast.bind(this), total: this.getTotal.bind(this) }); } export { Profiler };