Tuesday, December 3, 2013

Math: Get Factors of X

function factors( n ){
  var
    u = Math.floor( Math.sqrt( n ) ),
    i,
    f = [],
    e = [];
  for( i = 1 ; i <= u; i++ ) {
    if( n % i == 0 ) {
      f.push( i );
      e.unshift( n / i );
    }
  }
  if( e[ 0 ] == u ) e.shift();
  return f.concat( e );
}

Here the minimized version (147 bytes)...
function factors(n,u,i,f,e){for(u=Math.sqrt(n)|0,i=1,e=[],f=[];i<=u;i++)if(n%i<1){f.push(i);e.unshift(n/i)}if(e[0]==u)e.shift();return f.concat(e)}

Wednesday, September 7, 2011

Safe ANSI Encoding (Better than Base64)

To take advantage of Data URI feature for image inline embedding, almost everyone use Base64 encoding.

Base64 encode array of bytes (array of 8 bits) into it's Radix-64 representation (hence the name is Base-"64"). It transform each 3 bytes (24 bits) of data into 4 bytes encoded string with 6 bits of original data in each encoded char. These 6 bits (000000b-111111b = 0-63) is an index to 64 characters table, in which those 64 characters are considered safe to textual transfer (i.e., embedding binary data within an HTML script).

The disadvanatage of this scheme is the inflation size of it's host script as Base64 encoded string to 4/3 times (33.3%) longer than the original data stream. Anyway, if the data is sent gunzipped, the inflation is greatly reduced (in many case, even smaller than the original data). So for conclusion, Base64 embedding is a very good solution if you can serve the page gunzipped (i.e., using mod_gzip in Apache or using PHP's compression libraries).

If for any reason you can't gunzip your page, you can consider another alternative to embed binary data in your page. One of the solution packed in LF JavaScript Library is SAE (Safe Ansi Encoding), in which 32 characters of control charset (ASCII 0 to 31) is encoded using leading-escape character (the copyright character / ASCII 169) with value modified to (x+64) and the rest is embedded as is after XOR-ed with 128 (as binary data contains a lot of low ASCII bytes, especially the null byte (ASCII 0), this XOR helps reduce size inflation up to 5 percents in average). Every SAE data string is prefixed with Æ$ (2 bytes chars) as encoded indicator.

The result of SAE encoding is ANSI string safe for textual transfer (with charset iso-8859-1 to allow byte-range data minus first 32 bytes control characters) with size inflation about 9-11% in average for common images (jpeg/gif/png). It's one third of size-overhead with it's Base64 counterpart. Average size inflation if page is gunzipped is only about 1-3% of it's original size.

Below is PHP function to encode SAE data string

function saeEncode($s){
  $r='$'.chr(198);
  for($i=0;$i<strlen($s);$i++)
    $r.=($c=chr($a=ord($s[$i])^128)).($c==$e?$e:$a==60?'{':$a<32?chr($a|64):'');
  return $r;
}

Implementation example:
$f=file_get_contents('myImg.jpg');
$encoded=saeEncode($f);
header('Content-type: text/plain; charset=iso-8859-1');
echo $f;

As you can see from code above, this encoder takes special caution for '<' character since it's interpreted by browser DOM parser as beginning of tag. This is necessary as SAE encoded string is intended to be embedded within element text (so javascript code can easily retrieved the data using element.innerText property before performing SAE decoding).

This is the portion from lfw.js code that serve SAE decoding...
String.prototype.sae=function(){
  var s=this,r='',l,x=i=-1,c,a;
  if(!s)return '';
  if(s.$(0,2)=='$Æ'){ //decode
    s=s.$(2);a=[];l=s.length-1;
    for(i=0;i<l;i++){
      c=s.o(i);
      if((c==169)&&(i<=l)){
        i++;c=s.o(i);
        if(c==123)c=60;
        else if(c!==169)c=c&31;
      }
      r+=chr(c^128);
    }
  }
  //else encode (see the script for complete reference)
  return r;
}
function SAE(s){
  s=_(s).innerText.sae();
  var r='',i=0,e,h=s.$(0,32);
  e=h.c('JFIF')?'jpeg':h.c('GIF')?'gif':h.c('PNG')?'png':'unknown';
  for(;i<s.L();i++)r+='%'+hx(s.o(i));
  return 'data:image/'+e+';charset=oem,'+r
}

Using SAE embedded data is easy, simply call SAE('element_id') to compose the URI string (example: to create image (320x240px) with data embedded in an element (can be any element that support innerText property) with id myImg, just type:
__img(SAE('myImg'),320,240);

Sunday, August 28, 2011

lf.js v0.9.0

//lf.js v0.9.0 (c)2011 Ferdinand Liu [GNU Lesser GPL v3]
//http://code.google.com/p/lf-js/
D=document;W=window;sR=0;M=Math;IE=('\v'=='v');
function N(n){return !isNaN(n)}
function O(v){return v==null}
function trim(s){if(s&&s.length>0)return s.replace(/^\s|\s$/,'');else return ''}
function I(f){return parseInt(f)}
function div(a,b){return I(a/b)}
function rep(f,r,s){return s.replace(new RegExp(f,'g'),r)}
function CF(f){if(typeof(f)=='function')f()}
function _iO(e){return typeof(e)=='object'}
function fe(a,f){for(var i=0;i<a.length;i++)f(a[i])}
function _(i){if(!_iO(i))i=D.getElementById(i);return i}
function _h(i,h){i=_(i);if(O(i))return;if(!O(h)){i.innerHTML=h;CF(sR);return i}else return i.innerHTML}
function _a(i,a,v){i=_(i);if(v){i.setAttribute(a,v);return i}return i.getAttribute(a)}
function _t(t){return D.getElementsByTagName(t)}
function _C(e,c){var n=_(e).className;return (c==n)||((' '+n+' ').indexOf(' '+c+' ')>-1)}
function _CA(e,c){if(!_C(e,c))_(e).className=trim(_(e).className+' '+c);return e;}
function _CR(e,c){if(_C(e,c))_(e).className=trim(_(e).className.replace(c,''))}
function __(t){return D.createElement(t)}
function _ac(p,c){p.appendChild(c);return c}
function _z(e){e=_(e);if(e)e.parentNode.removeChild(e)}
function _V(e,v,f){e=_(e);if(e.addEventListener)e.addEventListener(v,f,false);else e.attachEvent('on'+v,f)}
function _VC(e){e=e?e:W.event;if(e.stopPropagation)e.stopPropagation();if(e.preventDefault)e.preventDefault();e.cancelBubble=e.cancel=!0;return e.returnValue=!1}
function _VR(e,v,f){e=_(e);if(e.removeEventListener)e.removeEventListener(v,f,!1);else e.detachEvent('on'+v,f)}
function $V(e,v){e=_(e);if(v){e.value=v;return e};return e.value}
function _L(e,u,f){e=_(e);_a(e,'src',u);if(f){_V(e,'load',f)}}
function _S(u,cb,t){var s=_a(__('script'),'type','text/javascript'),H=_t('head')[0],d=1,f=function(){if(d){d=0;if(cb)cb();if(t)_z(s)}};_ac(H,s);_L(s,u,f);if(IE)setTimeout(f,1000);}
function _c(c){var r=[];fe(_t('*'),function(e){if(_C(e,c))r.push(e);});return r}
function _s(e,s){_a(e,'style',s)}
function _d(i){return _(i).style.display}
function show(i){_(i).style.display='block';CF(sR)}
function hide(i){_(i).style.display='none';CF(sR)}
function _X(e,f){_V(e,'click',f)}
function XD(i){var a='A'+i;if(_C(a,'H')){hide(i);_CR(a,'H');}else{show(i);_CA(a,'H');}return false}
function c$$(c){var e=c.charAt(c.length-1),i=(e=='}'),a;if(i&&!IE){a=__('style');a.innerText=c;}else{if(i)c='data:text/css,'+escape(c);a=_a(_a(__('link'),'rel','stylesheet'),'href',c)};_ac(_t('head')[0],a)}

(function(){var a,f,m='DOMContentLoaded',r='onreadystatechange',l='load',z=!1;if(A=W.addEventListener){a=function(g){A(m,g,z);A(l,g,z)};f=function(g){R=W.removeEventListener;R(m,g,z);R(l,g,z)}}else{if(A=D.attachEvent){a=function(g){A(r,g);A(l,g)};f=function(g){R=D.detachEvent;R(r,g);R(l,g)}}}var e=null,b=z;function d(){b=true;f(d);if(!e){return}for(var g=0;g<e.length;g++)e[g]();e=null}function c(g){if(b){g();return}if(!e){e=[];a(d)}e.push(g)}W.OnReady=W.$R=c})();

function VP(t){var b=_t('body')[0],i='img',s=__('div'),l=__(i),i=__(i),y;
_s(s,'position:absolute;left:0;top:0;right:0;bottom:0;background:transparent url(//www.keran.org/Q/img/t.png);text-align:center;z-index:999;');_ac(b,s);
_L(l,'/img/loading.gif',function(){_s(l,'margin-top:'+div(s.offsetHeight-i.height,2)+'px');_ac(s,l);_L(i,t,function(){y=div(s.offsetHeight-i.height,2);y=(y>0)?y:0;_s(i,'border:5px solid #fff;max-width:95%;max-height:95%;margin-top:'+y+'px');_z(l);_ac(s,i);});});Z=function(){_z(s);};_X(i,Z);_X(s,Z);}