Created
August 11, 2023 15:59
-
-
Save terrysahaidak/0fedc8b76c3292a4d571c9a0a2170c0d to your computer and use it in GitHub Desktop.
measure utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createDebounceAverage( | |
title: string, | |
phase: string, | |
delay: number = 100 | |
) { | |
let values: number[] = []; | |
let timeout: NodeJS.Timeout; | |
return (value: number) => { | |
clearTimeout(timeout); | |
values.push(value); | |
timeout = setTimeout(() => { | |
const total = values.reduce((acc, curr) => acc + curr); | |
const max = Math.max(...values).toFixed(2); | |
const min = Math.min(...values).toFixed(2); | |
// it won't log it for some reason when i don't String() it | |
const count = String(values.length); | |
const average = String((total / values.length).toFixed(2)); | |
global.console.log( | |
`${phase}: ${title} (${count}) - ${average}ms (max: ${max}ms; min: ${min}ms) - total: ${total}` | |
); | |
values = []; | |
}, delay); | |
}; | |
} | |
const timeoutRegistry = new Map<string, any>(); | |
function createOrResolveDebounce(id: string, phase: string, delay?: number) { | |
const key = phase + id; | |
if (!timeoutRegistry.has(key)) { | |
timeoutRegistry.set(key, createDebounceAverage(id, phase, delay)); | |
} | |
return timeoutRegistry.get(key); | |
} | |
export function measureAverage(name: string, every = false, delay = 100) { | |
const onExec = createOrResolveDebounce(name, 'average', delay); | |
return (fn: (...args: any[]) => any) => { | |
return function (this: any, ...args: any[]) { | |
const start = global.performance.now(); | |
const result = fn.apply(this, args); | |
const time = global.performance.now() - start; | |
onExec(time); | |
if (every) { | |
global.console.log(`exec: ${name} - ${time.toFixed(2)}ms`); | |
} | |
return result; | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment