0

So I have a function that is recursive for inverting colors. Here is the code:

function invert(id,what){
    var color = $(id).css(what);
    var matchColors = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
    var match = matchColors.exec(color);
    var r = (255 - match[1]).toString() + ",";
    var g = (255 - match[2]).toString() + ",";
    var b = (255 - match[3]).toString();
    answer = 'rgb(' + r + g + b + ')' ;
    $(id).css(what,answer);
};

So essentially I have a function that can be called in many instances (clicks of specific ids, hover on specific classes, etc.) and I do not know them all. But I need to know every single time this function gets called. How can I have an outside line of code that sets a variable equal to the amount of times the function has been called?

Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128

2 Answers2

6

Wrap your function.

var wrapped = (function wrapper(present) {
    function wrapping() {
        ++wrapping.count; // increment invocation count
        return present.apply(this, arguments);
    }
    wrapping.count = 0; // counter, avaliable from outside too
    return wrapping;
}(invert));

If you need to call it invert too, re-assign invert after.

invert = wrapped;
invert.count; // 0
invert();
invert.count; // 1
invert();
invert.count; // 2
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • please re-read the question...I have made an edit so that it may be possible completely outside the original function as the function is no longer recursive – Ryan Saxe Jun 19 '13 at 22:30
  • @RyanSaxe are you saying that the function `invert` is declared in a scope you don't have access to? – Paul S. Jun 19 '13 at 22:35
  • This works, although I am going to post a question to see if it is possible to detect becuase I am curious anyways – Ryan Saxe Jun 19 '13 at 22:47
0

I am not sure what your exact scenario is, but maybe you could override the function with a wrapper:

var invertOriginal = invert;
var counter = 0;

var invert = function(id, what, max) {
  invertOriginal(id, what, max); 

  // do counter stuff here, e.g.
  counter++; 
};
compid
  • 1,313
  • 9
  • 15
  • can't change original function – Ryan Saxe Jun 19 '13 at 22:23
  • this doesn't change the original function. It simply "renames" the function and calls the renamed version. You can use this code without modifying the original source – compid Jun 19 '13 at 22:30
  • please re-read the question...I have made an edit so that it may be possible completely outside the original function as the function is no longer recursive – Ryan Saxe Jun 19 '13 at 22:32