Encoding number using web-safe chars

Benchmark created by WTK on


Preparation HTML

<script>
  var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  
  encode_py = function(n) {
   var s = '',
       r, tmp;
   while (n != 0) {
    tmp = Math.floor(n / 64);
    r = n % 64;
    n = tmp;
    s = alphabet[r] + s;
   }
   return s;
  }
  
  encode_ct = function(a) {
   var b = "",
       c;
   while (a != 0) {
    c = a & 63;
    a >>>= 6;
    b = alphabet[c] + b
   }
   return b;
  }
  
  function encodeNumber(num) {
   var encodeString = "";
  
   while (num >= 0x20) {
    encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
    num >>= 5;
   }
  
   encodeString += (String.fromCharCode(num + 63));
   return encodeString;
  }
  
  function encodeSignedNumber(num) {
   var sgn_num = num << 1;
  
   if (num < 0) {
    sgn_num = ~ (sgn_num);
   }
  
   return (encodeNumber(sgn_num));
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Stackoverlow method (from python)
var i = 20;
while (i--) {
 encode_py(Math.floor(Math.random() * 110));
}
ready
Clicktale method (from script)
var i = 20;
while (i--) {
 encode_ct(Math.floor(Math.random() * 110));
}
ready
Google maps method
var i = 20;
while (i--) {
 encodeSignedNumber(Math.floor(Math.random() * 110));
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.