Created
June 29, 2018 15:00
-
-
Save attatrol/dc9e5b17790f5b35dd66c4be3fbc96a2 to your computer and use it in GitHub Desktop.
typescript decorator for execution time check
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
/** | |
* Декоратор для проверки времени исполнения метода. | |
* Выводит в консоль 2 строки: | |
* - имя метода и список его параметров | |
* - время, за которое метод выполнился | |
* @param userMark пользовательский префикс строк | |
* @param consoleStyle css стиль строк в Chrome и FireFox, по умолчанию - синий текст | |
*/ | |
function LogPerformance(userMark?: string, consoleStyle: string = "color: #6495ed;"): MethodDecorator { | |
let PerfomanceCounter = 0; | |
const xLogger = function (msg: string): void { | |
isIE() ? console.log(msg) : console.log("%c " + msg, consoleStyle); | |
}; | |
const xDecorator = function (target: Object, propertyKey: string | symbol, | |
descriptor: TypedPropertyDescriptor<(...args: any[]) => any>): TypedPropertyDescriptor<(...args: any[]) => any> { | |
let xOriginalMethod = descriptor.value; | |
descriptor.value = function (): any { | |
let xMarker = ("0000" + (PerfomanceCounter++).toString()); | |
xMarker = xMarker.substring(xMarker.length - 4); | |
if (userMark) | |
xMarker = userMark + " " + xMarker; | |
let xArguments = new Array<string>(); | |
for (let arg of arguments) | |
xArguments.push(arg.toString()); | |
let xReport = xMarker + " Started " + propertyKey.toString() + "(" + xArguments.join(" ,") + ")"; | |
xLogger(xReport); | |
let xTimeMark: uint, | |
xEndCallback = function () { | |
xTimeMark = performance.now() - xTimeMark; | |
let xReport = xMarker + " Finished " + propertyKey.toString() + " in " + xTimeMark.toFixed(0) + " ms"; | |
xLogger(xReport); | |
}; | |
xTimeMark = performance.now(); | |
let xResult = xOriginalMethod.apply(this, arguments); | |
if (xResult instanceof Promise) { | |
xResult.then(xEndCallback, xEndCallback); | |
} else { | |
xEndCallback(); | |
} | |
return xResult; | |
}; | |
return descriptor; | |
} | |
return <MethodDecorator>xDecorator; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment