Skip to content

Instantly share code, notes, and snippets.

@deanrather
Created July 3, 2012 03:50
Show Gist options
  • Save deanrather/3037532 to your computer and use it in GitHub Desktop.
Save deanrather/3037532 to your computer and use it in GitHub Desktop.
_ = require('underscore');
/**
* Changes a string like "hello world" to "Hello world"
*/
_.ucFirst = function(str)
{
if(typeof str != 'string') throw new Error("Non-string provided");
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
};
/**
* Changs a string like "hello_world" to "HelloWorld"
*/
_.lower_underscore2UpperCamelCase = function(str)
{
if(typeof str != 'string') throw new Error("Non-string provided");
str = str.split('_');
var a = '';
var length = str.length;
for (var i=0; i<length; i++) { a += _.ucFirst(str[i]);}
return a;
};
/**
* Construct an object given a string representing the object.
* Eg. _.constructObject('foo.bar.Baz') Would return the Baz object from the foo.bar namespace
* NOTE: This function may not work, if using the JSKK framework, use $JSKK.namespace(str); instead
*/
_.objectFromString = function(str)
{
if(typeof str != 'string') throw new Error("Non-string provided");
var parts = str.split('.');
var nextObjectName = parts[0];
var object = global[nextObjectName];
var length = parts.length;
if (Object.isDefined(object) && typeof object == 'object')
{
for (var i=1; i<length; i++)
{
nextObjectName = parts[i];
if (Object.isDefined(object[nextObjectName]) && typeof object[nextObjectName] == 'object')
{
object = object[nextObjectName];
}
else
{
throw new Error('Error! object "'+str+'" cannot be loaded. '+nextObjectName+' is not an object');
}
}
}
else
{
throw new Error('Error! '+nextObjectName+' is not a defined object');
}
if(typeof object != 'object') throw new Error('Error! loaded object "'+str+'" is not an object.');
return object;
};
_.pad = function(number, length)
{
var str = '' + number;
while(str.length < length)
{
str = '0' + str;
}
return str;
};
_.formatDate = function(date)
{
var dateStamp = '';
dateStamp += date.getFullYear();
dateStamp += '-';
dateStamp += date.getMonth()+1;
dateStamp += '-';
dateStamp += date.getDate();
dateStamp += '_';
dateStamp += _.pad(date.getHours(), 2);
dateStamp += '-';
dateStamp += _.pad(date.getMinutes(), 2);
dateStamp += '-';
dateStamp += _.pad(date.getSeconds(), 2);
dateStamp += '_(';
dateStamp += date.getMilliseconds();
dateStamp += ')';
return dateStamp;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment