Pages

Saturday, June 12, 2010

timestampToString, Google's obfuscated code sample

When we search on Google, we sometimes see a time-stamp on the results.

Example:


What code does that job?

Well, here it is:
function sa(a,c){var b=c-a;if(b<86400)if(b<45)return"seconds ago";else if(b<105)return"1 minute ago";else if(b<3345){b=Math.floor(b/60)+(b%60>=45?1:0);return"1 minutes ago".replace("1",b+"")}else if(b<6600)return"1 hour ago";else{b=Math.floor(b/3600)+(b%3600>=3E3?1:0);return"1 hours ago".replace("1",b+"")}return g}

1-liner (kinda :-) obfuscated JavaScript code. Yeah, Google obfuscates the source code which is revealed to the public. Most function names, along with constant values, and white-space, are removed or replaced with shorter, meaningless names.

To get the code, go to Google home page, and use whatever option your favorite browser provides for viewing the source code.  In there, search for a URL string like this one:
/extern_js/f/CgJlbhICZ3IrMA ... BROAIsKzBaOAAsgAIV/0JBXC50vuSQ.js

If you attach it at the end of the Google URL, you'll get the whole source code.
ie, http://google.com/extern_js/...

Now, with a proper indentation, sa function becomes readable:
function sa(a, c) {
  var b = c - a;
  if (b < 86400)
      if (b < 45)
         return "seconds ago";
      else if (b < 105)
         return "1 minute ago";
      else if (b < 3345) {
         b = Math.floor(b / 60) + (b % 60 >= 45 ? 1:0); 
         return "1 minutes ago".replace("1", b + "")
      }
      else if (b < 6600)
         return "1 hour ago";
      else {
         b = Math.floor(b/3600) + (b%3600 >= 3E3 ? 1:0);
         return "1 hours ago".replace("1", b + "")
      }
  return g
}

If we know JavaScript, or another programming language with similar syntax, it's pretty easy to see that the time-stamp is displayed only on pages that were updated, in Google Index, in less than a day (86400 = 24 x 60 x 60 seconds).

Here is the final (unobfuscated) version, written in Python this time:
import math
def timestampToString(currentTime, modifiedTime):
   delta = currentTime - modifiedTime
   if delta < 86400:
      if delta < 45:
         return "seconds ago"
      elif delta < 105:
         return "1 minute ago"
      elif delta < 3345:
         delta = math.floor(delta / 60) + (1 if delta % 60 >= 45 else 0)
         return "%i minutes ago" % delta
      elif delta < 6600:
         return "1 hour ago";
      else:
         delta = math.floor(delta / 3600) + (1 if delta % 3600 >= 3000 else 0)
         return "%i hours ago‚" % delta
   return False

Did you notice that the value 3000 was, in the equivalent scientific notation, 3E3? Cool ;-)

No comments:

Post a Comment