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:

} 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.

  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

comments powered by Disqus