Thursday, May 14, 2009

RegExp escape function

RegExp.escape = (function() {
var punctuationChars = /([.*+?|/(){}[\]\\])/g;
return function(text) {
return text.replace(punctuationChars, '\\$1');
}
})();

var str = RegExp.escape('a+b/c*d$ ^{.}');
var reg = new RegExp(str);


Reference: http://simonwillison.net/2006/Jan/20/escape

Wednesday, May 13, 2009

Write excel tool for ruby

require 'rubygems'
require 'writeexcel'

# Create a new Excel Workbook
workbook = Spreadsheet::WriteExcel.new('ruby.xls')

# Add worksheet(s)
worksheet = workbook.add_worksheet
worksheet2 = workbook.add_worksheet

# Add and define a format
format = workbook.add_format
format.set_bold
format.set_color('red')
format.set_align('right')

# write a formatted and unformatted string.
worksheet.write(1, 1, 'Hi Excel.', format) # cell B2
worksheet.write(2, 1, 'Hi Ruby.') # cell B3

# write a number and formula using A1 notation
worksheet.write('B4', 3.14159)
worksheet.write('B5', '=SIN(B4/4)')

# write to file
workbook.close

Tuesday, May 12, 2009

Non-blocking JavaScript

Include via DOM

var js = document.createElement('script'); 
js.src = 'myscript.js'; 
var h = document.getElementsByTagName('head')[0]; 
h.appendChild(js);

Non-blocking JavaScript
  And what about my inline scripts?
  Setup a collection (registry) of inline scripts

Step 1
Inline in the <head>:
var myapp = { 
   stuff: [] 
}; 

Step 2
  Add to the registry
Instead of:
  alert('boo!');
Do:
  myapp.stuff.push(function(){ 
    alert('boo!'); 
  );

Step 3
  Execute all

var l = myapp.stuff.length;  
var l = myapp.stuff.length;  
for(var i = 0, i < l; i++) { 
myapp.stuff[i](); 

Premature optimization

Knuth: The premature optimization is the root of all evil.

Crockford: Make it right before you make it fast.