Tag Archives: Javascript

Code of the Day: Javascript Date.prototype.setDay()

In Javascript, I find it strange how `Date.prototype.getDay()` in defined but `Date.prototype.setDay()`.
So here’s the code for `Date.prototype.setDay()`.

// Sets the Date object to the day of the week.
// @param {Number} - dayIndex must be from 0 - 6, where 0 is sunday.
// @return {Number} returns the primitive value of the Date object.
Date.prototype.setDay = Date.prototype.setDay || function (dayIndex) {
	dayIndex = Math.floor(+dayIndex);
	if (dayIndex < 0 || 6 < dayIndex) {
		throw new Error("Must pass integer between 0-6, where sunday is 0.");
	}
	this.setDate( this.getDate() + dayIndex - this.getDay() );
	return this.valueOf();
};

Demo 1

var a = new Date(Date.parse("Feb 1, 2014"));
a.setDay(0);
console.log(a.toDateString() === "Sun Jan 26 2014" );
a.setDay(6);
console.log(a.toDateString() === "Sat Feb 01 2014" );

Demo 2

// Prings the Monday - Friday for the current day.
var getWeekString = function () {
	var days = [],
		date = new Date();
 
	for (var i = 1, len = 6; i < len; i++) {
		date.setDay(i)
		days.push("## " + date.toDateString() );
	}
	return days;
};
console.log(getWeekString().join("\n\n"));

If you looking for a good Javascript Date library, checkout moment.js.

More info:
MDN Date Object

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter

Code of the day: Javascript Flatten()

/**
* Returns an array that contains non-array elements.
* If an element is an array, then the element is replaced by the content of the array.
* @param{Array} 
* @return{Array} return null if no arguments are passed.
* @example 
    flatten([[1,2],3,[4]]); // returns [1,2,3,4];
*/
var flatten = function(arr){
	if(!Array.isArray(arr)){
		return (arr === null || arr === undefined) ? null : [arr];
	}
	var result = [], obj;
	for(var i = 0, len = arr.length; i < len; i++){
		obj = arr[i];
		if(Array.isArray(arr)){
			obj = flatten(obj);
		}
		result = result.concat( obj );
	}
    return result;
};

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter

Code of the day: Javascript check if an object is empty

`isObjectEmpty()` is a function that will only return true if the passed an object that contains no keys.
This is different than jQuery.isEmptyObject() because the passed argument MUST be an object.

/**
* Check to see if an object has any keys.
* @param {Object} obj
* @return {Boolean}
* @author Larry Battle <bateru.com/news>
* @license WTFPL
**/
var isObjectEmpty = function( obj ) {
	var name;
	for ( name in obj ) {
		return false;
	}
	return obj != null && typeof obj === "object";
};

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter

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

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter