D
D
Dmitry2018-02-02 11:38:43
JavaScript
Dmitry, 2018-02-02 11:38:43

How to index the functions themselves?

There is a method to which a certain function is passed.
I need to keep track of how many times the same function has been passed to this method. Functions in the method come in a large number and often different ones, but among this flow there are calls to the same function.

MyClass.prototype.method = function(fn){
    fn.apply(this, []);
};

You can add all the functions into a regular array, and run through it in its entirety with each call, comparing the functions, but this is horrendous and slow:
var functions_array = [];
MyClass.prototype.method = function(fn){
    var found = false;
    for(var i=0; i<functions_array.length; i++){
        if( functions_array[i] === fn ){
            // Функцию уже вызывали
            found=True; break;
        }
    }
    if( !found ) functions_array.push(fn);
    fn.apply(this, []);
};

Is it possible, perhaps, to somehow index the function and generate a key?
var functions_storage = {};
MyClass.prototype.method = function(fn){
    var found = false;
    var key = index_function(fn);
    if( functions_storage[key] !== undefined ){
            // Функцию уже вызывали
            found=True;
    }
    if( !found ) functions_storage[key] = fn;
    fn.apply(this, []);
};

How can I form a `key` for a function so that it accurately identifies this function and catches exactly its repeated calls?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Melnikov, 2018-02-02
@dimanjy

function MyClass() {
  this.fnMap = new WeakMap();
}

MyClass.prototype.method = function(fn) {
  if (this.fnMap[fn]) {
    return;
  }
  this.fnMap[fn] = true;
  fn.apply(this, []);
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question