Add property to functions

Carina Syemyerdzhyan
19-01-2017

Functions are the first-class object in JavaScript. Functions have the same behavior as objects. We can easily add a property to a function!

Storing functions

Consider we need a collection of callbacks and we want to store these callbacks dynamically (only unique callbacks). The naive implementation is creating an array. Using a loop go through it. Add a new callback function and everytime check if the given callback exists. This approach has a poorly performance. Using a function property avoid this problem.

var store = {
  nextId: 1,
  cache: {},
  add: function(fn) {

    if (!fn.id) {
        fn.id = this.nextId++;
        this.cache[fn.id] = fn;
        return true;
    } 
  }
};

function helloCompeta(){}

store.add(helloCompeta);
console.log(store.cache);
store.add(helloCompeta);
console.log(store.cache);

Memorisation the previous computed value

The next example what I’d like to provide is how to memorize the previous computed value using a function property.
Consider we want to computed if the given number is prime or not.

function isPrime(value){
    if (!isPrime.answers)   {                   
        isPrime.answers = {}; 
    }
                    
    if (isPrime.answers[value] !== undefined) {
        return isPrime.answers[value];                  
    }
    
    var prime = value !== 1; // 1 is not a prime                
                    
    for (var i = 2; i < value; i++) {
        if (value % i === 0) {
            prime = false;
            break; 
        }
    }
    return isPrime.answers[value] = prime;
}

LEAVE A REPLY

you might also like