Code of the Day: Javascript Auto-complete date format MMDDYYYY

/**
* This function helps to autocomplete the date format MMDDYYY
* Converts M to 0M and MMD to MM0D. Ex. `1/` to `01/`, `01/1/` to `01/01/`
* Adds slash for MM and MMDD Ex. `01` to `01/`, `01/02` to `01/02/`
* Converts YY to YYYY. Ex. `01/01/01` to `01/01/2001`
*
* @param {String} str
* @return {String}
*/
var autocompleteMMDDYYYYDateFormat = function (str) {
        str = str.trim();
        var matches, year,
                looksLike_MM_slash_DD = /^(\d\d\/)?\d\d$/,
                looksLike_MM_slash_D_slash = /^(\d\d\/)?(\d\/)$/,
                looksLike_MM_slash_DD_slash_DD = /^(\d\d\/\d\d\/)(\d\d)$/;
 
        if( looksLike_MM_slash_DD.test(str) ){
                str += "/";
        }else if( looksLike_MM_slash_D_slash.test(str) ){
                str = str.replace( looksLike_MM_slash_D_slash, "$10$2");
        }else if( looksLike_MM_slash_DD_slash_DD.test(str) ){
                matches = str.match( looksLike_MM_slash_DD_slash_DD );
                year = Number( matches[2] ) < 20 ? "20" : "19";
                str = String( matches[1] ) + year + String(matches[2]);
        }
        return str;
};

Demo

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
TwitterLinkedInYouTube

Code of the Day: Chop up an array into groups using Underscore.js

Shrink an array into a group of smaller arrays using underscore.js

// Make sure to include underscore.js 
_.mixin({
    chunk : function (array, unit) {
        if (!_.isArray(array)) return array;
        unit = Math.abs(unit);
        var results = [],
        length = Math.ceil(array.length / unit);
 
        for (var i = 0; i < length; i++) {
            results.push(array.slice( i * unit, (i + 1) * unit));
        }
        return results;
    }
});

Example:

JSON.stringify( _.chunk([1,2,3,4,5,6,7,8,9], 2) ); 
// returns "[[1,2],[3,4],[5,6],[7,8],[9]]"

Here’s the same thing without using Underscore.js

var chunk = function (array, unit) {
	if (typeof array !== "object")
		return array;
	unit = Math.abs(unit);
	var results = [],
	length = Math.ceil(array.length / unit);
 
	for (var i = 0; i < length; i++) {
		results.push(array.slice(i * unit, (i + 1) * unit));
	}
	return results;
}

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
TwitterLinkedInYouTube

Code of the day: jQuery, Get comments from HTML elements.

Code of the day: Get comments from HTML elements.
Here’s a simple jquery plugin to get the comments from a HTML elements.

// source code for $.fn.getComments()
$(function () {
/**
* $.fn.getComments() is used to extract the html comments from a HTML elements.
* 
* @author Larry Battle <http://bateru.com/news/contact-me>
* @license MIT
* @date June 11, 2012
* @version 0.1
* @args {boolean} asArray - If true, returns an array of the comments values. 
		Otherwise returns jquery objects of the node comments.
* @example 
	HTML:
	<div id="example">I am a div. <!--Duh!--></div>
 
	Javascript: 
	$("#example").getComments(true) // returns [ "Duh!" ]
*/
	var getCommentsFromEl = function (el, asArray) {
		var result,
		$el = $(el).contents();
		result = $el.filter(function () {
				return this.nodeType == 8;
			});
		if (asArray) {
			result = $.makeArray(result.map(function () {
						return this.nodeValue;
					}));
		}
		return result;
	};
	$.fn.getComments = function (asArray) {
		return getCommentsFromEl(this, asArray);
	};
});

Demo and testcases here: http://jsfiddle.net/96rux/

Fork this on Github.com
https://github.com/LarryBattle/jQuery.getComments

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
TwitterLinkedInYouTube

Code of the Day: Javascript, create object without calling new on the Constructor

Here’s a simple trick to avoid having to call new on a constructor. All you have to do is have the constructor do it for you. Here’s how.

Check if the `this` variable is an instanceof of the Constructor. If not, then return a new instance of the constructor whiling passing the same arguments. `new ConstructorName(arg1, arg2, … argN)`.

If you call a constructor without using this trick, `this` will be referenced to the scope to which the constructor is contained within. Which in most cases is `window`.

Example:

var Person = function( name ){
    if(!(this instanceof Person)){
        return new Person(name);
    }
    this.name = name || "NA" ;
    return this;
};

Live Demo:*click the results tab*

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
TwitterLinkedInYouTube