Monthly Archive for February, 2010

jQuery Array Chunk plugin

Since I am working almost exclusively in jQuery, I am much more inclined to convert common utilities I have written to jQuery plugins, my latest is the JavaScript array chunk method.

You can see the complete code and a usage example below, or download the plugin via the jQuery plugin library.

Usage is as follows:

 
        (function($) {
 
        	$.chunk = function( array, chunkSize ) {
        	   var base = [], i, size = chunkSize || 5;
        	   for(i=0; i<array.length; i+=chunkSize ) { base.push( array.slice( i, i+chunkSize ) ); }	
        	   return base;
        	}
 
        })(jQuery);
 
        var myArray=["apple", "onion", "orange", "potato", "pear", "grape", "tomato"], myChunkedArray=[];
        myChunkedArray = $.chunk( myArray, 3);
        console.log( myChunkedArray )
 
        /*
            Output:
 
            myChunkedArray = [
                ["apple", "onion", "orange"],
                ["potato", "pear", "grape"],
                ["tomato"]
            ]
        */

jQuery Time Format Plugin

When it comes to real-time, there is nothing that says it like a cool time date display. That’s why I am releasing my jQuery.timeFormat() plugin. It’s extremely simple, it takes a timestamp from the server in seconds and calculates the difference. The return response is of the format:

  • Now
  • 2 mins ago
  • 5 hours ago
  • 1 day ago
  • January 15

This is the same logic I use in my last.fm wordpress plugin. The code is below or available via the jQuery site.

/*
    name : timeFormat
    file : jquery.timeFormat.js
    author : gregory tomlinson
    Dual licensed under the MIT and GPL licenses.
    ///////////////////////////
    ///////////////////////////        
    dependencies : jQuery 1.4.2
    ///////////////////////////
    ///////////////////////////
 
*/
 
(function($) {
 
    /*
        Format the time by:
            1. taking existing timestamp from server
            2. calculate current time
            3. find difference
            4. Display:
                    Now
                    2 mins ago
                    3 hours ago
                    1 day ago
                    January 15
    */
 
    $.timeFormat = function( timestamp ) {
        var time = handleDate( timestamp );
        return time;
    } 
    function handleDate( timestamp ) {
        var n=new Date(), t, ago = " ";
        if( timestamp ) {
          t =   Math.round( (n.getTime()/1000 - timestamp)/60 );
          ago += handleSinceDateEndings( t, timestamp );
        } else {
            ago += "";
        }
        return ago;
    }    
    function handleSinceDateEndings( t, original_timestamp ) {
        var ago = " ", date;
        if( t <= 1 ) {
            ago += "Now";
        } else if( t<60) {
            ago += t + " mins ago";
        } else if( t>= 60 && t<= 120) {
            ago += Math.floor( t / 60 ) + " hour ago"
        } else if( t<1440 ) {
            //console.log(t)
            ago += Math.floor( t / 60 )  + " hours ago";
        } else if( t< 2880) {
            ago +=  "1 day ago";
        } else if( t > 2880  && t < 4320 ) {
            ago +=  "2 days ago";
        } else {
            date = new Date( parseInt( original_timestamp )*1000 ) 
            ago += months[ date.getMonth() ] + " " + date.getDate();
        }
        return ago;
    }
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
})(jQuery);

Tweet your Favorite Tracks, automagically

Earlier this week, I wrote a tiny little app, which tweets my favorite music. You can read more about the concept here. This is a technical post to explain how you can leverage this app for your own enjoyment.

First, you will need to download the code. Then you will need to obtain the following items:

Once you have obtained these items, you will need a computer that is always plugged into the internet or a web server where you can run cron jobs. I am running the script on this server.

Open the track_lover.php file, which you should have gotten from here, and update the following lines, replacing ‘xxx’ with real values:

    // TWITTER
    define("TWITTER_USERNAME", "xxx");
    define("TWITTER_PASSWORD", "xxx");
 
    // last.fm
    define("LASTFM_USER", "xxx");    
    define("LASTFM_API", "xxx");    
 
    // bit.ly via j.mp
    define("BITLY_USER", "xxx");
    define("BITLY_API", "xxx");

Once you save the file, you will be all set to turn on The cron job entry may look as follows

# run every two minutes
*/2 * * * * /usr/local/bin/php /path/to/the/script/trackLover/track_lover.php > /dev/null 2>&1

That’s it, you should be up and running tweeting your favorite tracks. Enjoy!

Intersection of Geek and Music

I absolutely love the intersection of geek and music.

Recently, I wrote a tiny little app that does for me something that is irritating to do manually, sharing my favorite music at this moment. Essentially, it tweets to the world the track I have listened to a track at least 3 times in the last hour.

I am leveraging several APIs to create this app. The always wonderful last.fm API, as well as the bit.ly (awesome) API and the Twitter API. The real trick is taking advantage of the upcoming version 3 API from bit.ly. In the latest bit.ly API, bit.ly returns a boolean whether the recently shortened track is a new ‘hash’ or not. Meaning, if it has not been shortened by me before, it returns true. Instead of needing to attach a database to this app, I am just checking this boolean. Normally, I would consider this abusive, however, with all the preconditions of my script, I rarely even ask bit.ly if this shorten is ‘new’.

If it wasn’t for the descriptive potential of bit.ly, I would need to establish a flat file, or database to handle this logic check. Eventually, if they alter the API, this will become a nessecity, but for the time being I am leveraging this functionality.

Shortly, I will attempt to release a new wordpress plugin or cron that leverages all three APIs, but for the time being the code is a bit messy. If you are interested, please reach out in the comments below with an email address and I am happy to share the code. Otherwise, enjoy my twitter stream and all the music I am addicted too.