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.
12345678910111213141516171819202122232425
functiongetOffOrigin(src,origin){// Use src and origin as cache keyvarcacheKey=JSON.stringify(Array.prototype.slice.call(arguments));if(!getOffOrigin.cache[cacheKey]){varnative=getOriginObject(origin);varcurrent=getOriginObject(src);if(current.protocol=='http:'){// Display http:// protocol anywaygetOffOrigin.cache[cacheKey]=current.protocol+'//'+current.hostname;}elseif(native.protocol==current.protocol&&native.hostname==current.hostname&&native.port==current.port){// Same origin policygetOffOrigin.cache[cacheKey]='';}elseif(current.protocol=='app:'){// Avoid displaying app:// protocolgetOffOrigin.cache[cacheKey]='';}else{getOffOrigin.cache[cacheKey]=current.protocol+'//'+current.hostname;}}returngetOffOrigin.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.