Nov 17, 2010

Pattern matching shorthand in function definition

Pattern matching is powerful construct in F#, but sometime it is confusing to beginner, below is pattern matching shorthand in function definition. The paramter is implied in the matching pattern, essentially you can rewrite it as below.


let listOfList = [[2; 3; 5]; [7; 11; 13]; [17; 19; 23; 29]]

let rec concatList =
    function head :: tail -> head @ (concatList tail)
            | [] -> []

//let rec concatList l =
//    match l with
//    | head :: tail -> head @ (concatList tail)
//    | [] -> []

let primes = concatList listOfList;

printfn "%A" primes

Nov 15, 2010

benchmark you javascript

Here is script that is used to benchmark jQuery.

// Runs a function many times without the function call overhead
function benchmark(fn, times, name){
 fn = fn.toString();
 var s = fn.indexOf('{')+1,
  e = fn.lastIndexOf('}');
 fn = fn.substring(s,e);
 
  return benchmarkString(fn, times, name);
}

function benchmarkString(fn, times, name) {
  var fn = new Function("i", "var t=new Date; while(i--) {" + fn + "}; return new Date - t")(times)
  fn.displayName = name || "benchmarked";
  return fn;
}

Nov 13, 2010

jQuery object is an array like object

jQuery object is not an Array object, but it looks like an array. The following code how this is implemented?

var o = {"0":1, "1": 2, length:2};
var a = [].slice.call(o, 0);
alert(a); // 1, 2


//or you can do this
var o = {}
o[0] = 1;
o.length = 1;
o[1] = 2;
o.length = 2;
var a = [].slice.call(o, 0);
alert(a); // 1, 2

//or you can do this
var o = {};
[].push.call(o, 1);
[].push.call(o, 2);
var a = [].slice.call(o, 0);
alert(a); // 1, 2

object toString

The memeber toString of different object is redefined in their prototype, for example, Object.prototype.toString is different from Array.prototype.toString, to apply a Object.prototype.toString to an array object, we can write the following code

var toString = Object.prototype.toString;
alert(toString.call([1, 2])); //[object Array]
alert([1, 2].toString()); //1,2

This will return the type of the object, "[object Array]"

using each function over "for" construct

jquery.each

jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});