Thinking about starting a project. Global Flourish object, just useful static methods.
Here is humanize() and underscorize() as close as possible to PHP implementation:
Flourish = {};
Flourish.humanizeCache = {};
Flourish.underscorizeCache = {};
/**
* Port of fGrammar::underscorize from Flourish.
*
* @param {string} str
* @return {string}
*/
Flourish.underscorize = function (str) {
if (Flourish.underscorizeCache[str]) {
return Flourish.underscorizeCache[str];
}
var original = str;
str = str.charAt(0).toLowerCase() + str.substr(1);
if (str.indexOf('_') !== -1 && str.toLowerCase() === str) {
}
else {
var old;
do {
old = str;
str = str.replace(/([a-zA-Z])([0-9])/, '$1_$2');
str = str.replace(/([a-z0-9A-Z])([A-Z])/, '$1_$2');
} while (old !== str);
str = str.toLowerCase(str);
}
Flourish.underscorizeCache[original] = str;
return str;
};
/**
* Port of fGrammar::humanize() from Flourish.
*
* @param {string} str
* @return {string}
*/
Flourish.humanize = function (str) {
if (Flourish.humanizeCache[str]) {
return Flourish.humanizeCache[str];
}
var original = str;
if (str.indexOf(' ') === -1) {
if (str.indexOf('_') !== -1) {
str = Flourish.underscorize(str);
}
}
var regex = /(\\b(api|css|gif|html|id|jpg|js|mp3|pdf|php|png|sql|swf|url|xhtml|xml)\\b|\\b\\w)/;
str = str.replace(/_/g, ' ').replace(regex, function (str, p1) {
return p1.charAt(0).toUpperCase();
});
Flourish.humanizeCache[original] = str;
return str;
};
Just for fun here's what Closure Compiler spits out pretty-printed:
Flourish = {b: {},d: {}};
Flourish.i = function(a) {
if (Flourish.d[a])
return Flourish.d[a];
var b = a, a = a.charAt(0).toLowerCase() + a.substr(1);
if (!(a.indexOf("_") !== -1 && a.toLowerCase() === a)) {
var c;
do
c = a, a = a.replace(/([a-zA-Z])([0-9])/, "$1_$2"), a = a.replace(/([a-z0-9A-Z])([A-Z])/, "$1_$2");
while (c !== a);
a = a.toLowerCase(a)
}
return Flourish.d[b] = a
};
Flourish.h = function(a) {
if (Flourish.b[a])
return Flourish.b[a];
var b = a;
a.indexOf(" ") === -1 && a.indexOf("_") !== -1 && (a = Flourish.i(a));
a = a.replace(/_/g, " ").replace(/(\\b(api|css|gif|html|id|jpg|js|mp3|pdf|php|png|sql|swf|url|xhtml|xml)\\b|\\b\\w)/, function(a, b) {
return b.charAt(0).toUpperCase()
});
return Flourish.b[b] = a
};