RSS | Archive | Random | E-mail

About

Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.

Links

Codepuzzling main site
Development site
ByteStrike italian blog
Follow me on Twitter

My Life Style

while(passion) {
  try {
    myLife.run();
  }catch(LifeExceptions) {  
    stronger++;
    continue;
   }
}

Following

4 August 10

[JS] Fastest way for searching a monodimensional array?

var myAr = ['apple', 5, 6];
if(String('^' + myAr.join('^')).indexOf("^5") != -1)
  console.log("found!");
else
  console.log("not found :(");

Tags: javascript
Comments (View)
27 July 10

[JS] jQuery random number plugin

I’ve taken this little piece of code around the Web (sorry, I forgot the original source) and it’s a good example on how to develop a plugin for jQuery:

/** Usage:
* $.random(int);
* $.randomBetween(min, max); */
jQuery.extend({
	random: function(X) {
		return Math.floor(X * (Math.random() % 1));
	},
	randomBetween: function(MinV, MaxV) {
	  return MinV + jQuery.random(MaxV - MinV + 1);
	}
});

Comments (View)
17 November 09

[Links] Online services and tools for regex testing

Regular expressions are a very powerful weapon for the developer if he can deals with all the pain of testing, debugging and learning the quirks of this matter. I’m collecting some links to be red one day, when I’ll got time to dive more deeply in the argument:

Comments (View)
22 September 09

[JS] How to get the time and unixtime

Self explanatory code:

var T = {
 getUnixTime: function() {
   return parseInt(new Date().getTime().toString().substring(0, 10));
 },
	
// format hh:mm:ss
getTime: function() 
{
  var d= new Date();
  var time = new Array();
  var hours = d.getHours();
  time.push(hours);
  var minutes = d.getMinutes().toString().length < 2 ? "0"+d.getMinutes() : d.getMinutes(); 
  time.push(minutes);
  var seconds = d.getSeconds().toString().length < 2 ? "0"+d.getSeconds() : d.getSeconds(); 
  time.push(seconds);
  	
  return time.join(":");
 }
}	
Update: I’ve just discovered that Syntax Highlighter code doesn’t work well with < > symbols in javascript code….

Comments (View)
Posted: 10:15 AM

[JS] How to extend Array object to get the index of an its value

The code is self explanatory: you have an array and you want to know what index has the element “pippo” or “5”. So I extended the array object with prototype keyword to scan the array and to return the index if found, -1 otherwise.

var points = [56,12,36];

Array.prototype.getIndex = function(aVal) 
{
   for(item in this)
     if(aVal == this[item])
       return item;
   
   return -1;
}

console.log(points.getIndex(36));
If you have Firefox or Safari (maybe in IE8 too, I dunno), watch at the console and you’ll see2 as result.

Comments (View)
10 September 09

[jQuery] How to use Prototype or MooTools with jQuery

Since many libraries make use of the $ identifier, we need a way to prevent collisions between these names. jQuery provides a method called .noConflict() to return control of the $ identifier back to other libraries. Typical usage of .noConflict() follows the following pattern:

First, the other library (Prototype in this example) is included. Then, jQuery itself is included, taking over $ for its own use. Next, a call to .noConflict() frees up $, so that control of it reverts to the first included library (Prototype). Now in our custom script we can use both libraries—but whenever we need to use a jQuery method, we need to use jQuery instead of $ as an identifier.

Comments (View)
Posted: 12:11 PM

[jQuery] How to add a CSS class to external links

 // apply a class to all <a> which respect the filter selection.
  $('a').filter(function() {
    return this.hostname && this.hostname != location.hostname;
  }).addClass('external');

Comments (View)
3 September 09

[JS] Firefox debugging with Firebug Console API

I’ve found always useful using Bin-Blog’s dump function to explore the properties of an object or an array (like a PHP print_r) but now I’ve discovered that console.dir function does the same:

a = ['a', 1, true];
console.dir(a);
console.dir function will produce in output console this result:
>>> a = ['a', 1, true]; console.dir(a)
	
0	"a"
1	1
2	true

Comments (View)
1 July 09

[JS] How to test if a variable is defined

// returns 1 if defined, 0 otherwise.
function isDefined(anObj) {
   switch(typeof(anObj)) {
    	case "string": if(anObj != "") return 1; else return 0; 
    	case "undefined": return 0;
    	case "object": if(anObj != null) return 1; else return 0;
    	default: return 0;
   }
}

Comments (View)
5 June 09

Trim,ltrim & rtrim in #javascript

andreaolivato:

Simple class to trim,ltrim and rtrim as it’s common in other languages.

trim = {
	both : function(str,ch) { # Equivalent to trim
		return trim.lead(trim.trail(str,ch),ch);
	},
	lead : function(str,ch) { # Equivalent to ltrim
		if (!ch)
			ch="\\s"
		return str.replace(
			new RegExp("^["+ch+"]+", "g"), ""
		);
	},
	trail : function(str,ch) { # Equivalent to rtrim
		if (!ch)
			ch="\\s";
		return str.replace(
			new RegExp("["+ch+"]+$", "g"), ""
		);
	}
}

You can use it like this

s = "  string  ";
# Trim both left and right, every type of char
alert(trim.both(s));
# Trim only right, and just look for \n
alert(trim.trail(s,"\\n"));

Reblogged: andreaolivato

Tags: javascript
Comments (View)
Themed by Hunson. Originally by Josh