Javascript Memorization

- - posted in javascript | Comments

As you know, function in javascript is also an object, you could use a property of the object to keep function result. This is called Memorization.

Today I have a chance to utilize this skill.

Please read codes below first:

1
2
3
4
5
} else if (getOffOrigin(app.frame.dataset.url ? app.frame.dataset.url : app.frame.src, origin)) {
  var subtitle = document.createElement('p');
  subtitle.textContent = getOffOrigin(app.frame.dataset.url ? app.frame.dataset.url : app.frame.src, origin);
  card.appendChild(subtitle);
}

getOffOrigin has to use some logic to compare the two arguments and return a string. The result wouldn’t change if the arguments are the same. Therefore, to avoid calling the function many times, the result could be stored in the function itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  function getOffOrigin(src, origin) {
    // Use src and origin as cache key
    var cacheKey = JSON.stringify(Array.prototype.slice.call(arguments));
    if (!getOffOrigin.cache[cacheKey]) {
      var native = getOriginObject(origin);
      var current = getOriginObject(src);
      if (current.protocol == 'http:') {
        // Display http:// protocol anyway
        getOffOrigin.cache[cacheKey] = current.protocol + '//' + current.hostname;
      } else if (native.protocol == current.protocol &&
          native.hostname == current.hostname &&
          native.port == current.port) {
        // Same origin policy
        getOffOrigin.cache[cacheKey] = '';
      } else if (current.protocol == 'app:') {
        // Avoid displaying app:// protocol
        getOffOrigin.cache[cacheKey] = '';
      } else {
        getOffOrigin.cache[cacheKey] = current.protocol + '//' + current.hostname;
      }
    }

    return getOffOrigin.cache[cacheKey];
  }
  getOffOrigin.cache = {};
  • If we only have one arguments we could use it as the key to cache directly. But we have multiple arguments in this case, we then use stringilized JSON to be the key.

  • Hence we don’t need to do the same thing every time we enter this function if the arguments are used before.

  • Have fun with your function cache!

Comments