Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Gavin Kistner http://phrogz.net/

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Splitting/Joining URLs

File.dirname "http://foo.com/bar/stuff.html"
#=> "http://foo.com/bar"

File.basename "http://foo.com/bar/stuff.html"
#=> "stuff.html"

File.split "http://foo.com/bar/stuff.html"
#=> ["http://foo.com/bar", "stuff.html"]

File.join( File.dirname("http://foo.com/bar/doc.html"), "relative_link.html" )
# => "http://foo.com/bar/relative_link.html"


(Originally by Ilmari Heikkinen on the ruby-talk mailing list.)

Loop through an array without wasteful lookups

Looking up the length of an array on each iteration of a loop is slow and inefficient (if the length of the array isn't changing).

If it's OK to iterate from back to front:
for ( var i=myArray.length-1; i>=0; --i ){
  ...
}


If you need to go from front to back:
for ( var i=0, len=myArray.length; i<len; ++i ){
  ...
}

Add a JS function for bounded random numbers

Math.randomMax = function(maxVal,asFloat){
	var val = Math.random()*maxVal;
	return asFloat?val:Math.round(val);
}


For a random integer between 0 and 10 (inclusive), simply:
var theNumber = Math.randomMax( 10 );


For a random float value between 0 and 10, pass a truth value to the second parameter:
var theNumber = Math.randomMax( 10, true );

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS