@applitools/monitoring-commons
Version:
152 lines (131 loc) • 3.26 kB
JavaScript
function makeTiming({parentPerformance = undefined, nowService = Date.now} = {}) {
const performance = parentPerformance || {}
/**
*
* @template T
* @param {string} name
* @param {()=>Promise<T>} f
* @returns {Promise<T>}
*/
function timeItAsync(name, f) {
const start = nowService()
return f().then(
(v) => ((performance[name] = (performance[name] || 0) + nowService() - start), v),
(v) => (
(performance[name] = (performance[name] || 0) + nowService() - start), Promise.reject(v)
),
)
}
/**
*
* @param {string} name
* @returns {()=>void}
*/
function getTimeItCallback(name) {
const start = nowService()
return () => {
performance[name] = (performance[name] || 0) + nowService() - start
}
}
/**
*
* @template T
* @param {string} name
* @param {()=>T} f
* @returns {T}
*/
function timeIt(name, f) {
const start = nowService()
try {
const ret = f()
performance[name] = (performance[name] || 0) + nowService() - start
return ret
} catch (err) {
performance[name] = (performance[name] || 0) + nowService() - start
throw err
}
}
return {
timeItAsync,
timeIt,
getTimeItCallback,
performance,
}
}
function makeOrderedTiming({parentPerformance = undefined, nowService = Date.now} = {}) {
let index = 0
const performance = parentPerformance || {}
/**
*
* @template T
* @param {string} name
* @param {()=>Promise<T>} f
* @returns {Promise<T>}
*/
function timeItAsync(name, f) {
const start = nowService()
const number = index
index++
const prefix = numberToPrefix(number)
const nameWithPrefix = `${prefix}. ${name}`
return f().then(
(v) => ((performance[nameWithPrefix] = nowService() - start), v),
(v) => ((performance[nameWithPrefix] = nowService() - start), Promise.reject(v)),
)
}
/**
*
* @param {string} name
* @returns {()=>void}
*/
function getTimeItCallback(name) {
const number = index
index++
const prefix = numberToPrefix(number)
const nameWithPrefix = `${prefix}. ${name}`
const start = nowService()
return () => {
performance[nameWithPrefix] = nowService() - start
}
}
/**
*
* @template T
* @param {string} name
* @param {()=>T} f
* @returns {T}
*/
function timeIt(name, f) {
const start = nowService()
const number = index
const prefix = numberToPrefix(number)
const nameWithPrefix = `${prefix}. ${name}`
index++
try {
const ret = f()
performance[nameWithPrefix] = nowService() - start
return ret
} catch (err) {
performance[nameWithPrefix] = nowService() - start
throw err
}
}
function numberToPrefix(number) {
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const digits = Math.floor(number / letters.length)
const remainder = number % letters.length
const zPrefix = digits ? new Array(digits - 1).fill('Z').join('') : ''
return zPrefix + letters[remainder]
}
return {
timeItAsync,
timeIt,
getTimeItCallback,
performance,
}
}
module.exports = {
makeTiming,
makeOrderedTiming,
}