Created
July 23, 2014 09:59
-
-
Save jitensachdeva/a5ea8254f7f67e259af9 to your computer and use it in GitHub Desktop.
Implement a Logger function that accepts a function you specify wraps it with a function that logs the start time and the finish time to the console and returns the decorated function. Demonstrate it by decorating an add function that accepts two numbers and returns the sum, and now also logs the start time and end time.
This file contains hidden or 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 getDateTime() { | |
| var now = new Date(); | |
| var year = now.getFullYear(); | |
| var month = now.getMonth()+1; | |
| var day = now.getDate(); | |
| var hour = now.getHours(); | |
| var minute = now.getMinutes(); | |
| var second = now.getSeconds(); | |
| if(month.toString().length == 1) { | |
| var month = '0'+month; | |
| } | |
| if(day.toString().length == 1) { | |
| var day = '0'+day; | |
| } | |
| if(hour.toString().length == 1) { | |
| var hour = '0'+hour; | |
| } | |
| if(minute.toString().length == 1) { | |
| var minute = '0'+minute; | |
| } | |
| if(second.toString().length == 1) { | |
| var second = '0'+second; | |
| } | |
| var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second; | |
| return dateTime; | |
| } | |
| var add = function(a,b) { | |
| console.log(a+b); | |
| return a+b; | |
| }; | |
| var subtract = function(a,b){ | |
| console.log(a-b); | |
| return a-b | |
| } | |
| var decorator = function (block){ | |
| return function(){ | |
| console.log("start time - " + getDateTime() ); | |
| block.apply(this,arguments); | |
| console.log("end time -" + getDateTime()); | |
| } | |
| }; | |
| var addDecorated = decorator(add); | |
| addDecorated(1,2); | |
| var subtractDecorated = decorator(subtract); | |
| subtractDecorated(3,4) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment