improve the breakUp user name algorithm, add some tests

This commit is contained in:
Sam 2013-06-28 13:56:38 +10:00
parent 966513a66d
commit e63bfd2f4c
3 changed files with 35 additions and 14 deletions

View File

@ -4,7 +4,26 @@ Discourse.Formatter = (function(){
var updateRelativeAge, autoUpdatingRelativeAge, relativeAge, relativeAgeTiny,
relativeAgeMedium, relativeAgeMediumSpan, longDate, toTitleCase,
shortDate;
shortDate, breakUp;
breakUp = function(string, maxLength){
if(string.length <= maxLength) {
return string;
}
var firstPart = string.substr(0, maxLength);
var betterSplit = firstPart.substr(1).search(/[A-Z_]/);
if (betterSplit >= 0) {
var offset = 1;
if(string[betterSplit+1] === "_") {
offset = 2;
}
return string.substr(0, betterSplit + offset) + " " + string.substring(betterSplit + offset);
} else {
return firstPart + " " + string.substr(maxLength);
}
};
shortDate = function(date){
return moment(date).shortDate();
@ -189,6 +208,7 @@ Discourse.Formatter = (function(){
autoUpdatingRelativeAge: autoUpdatingRelativeAge,
updateRelativeAge: updateRelativeAge,
toTitleCase: toTitleCase,
shortDate: shortDate
shortDate: shortDate,
breakUp: breakUp
};
})();

View File

@ -9,17 +9,7 @@ Handlebars.registerHelper('breakUp', function(property, options) {
prop = Ember.Handlebars.get(this, property, options);
if (!prop) return "";
tokens = prop.match(new RegExp(".{1,14}", 'g'));
if (tokens.length === 1) return prop;
result = "";
_.each(tokens,function(token,index) {
result += token;
if (token.indexOf(' ') === -1 && (index < tokens.length - 1)) {
result += "- ";
}
});
return result;
return Discourse.Formatter.breakUp(prop, 13);
});
/**
@ -320,4 +310,4 @@ Handlebars.registerHelper('faqLink', function(property, options) {
(Discourse.SiteSettings.faq_url.length > 0 ? Discourse.SiteSettings.faq_url : Discourse.getURL('/faq')) +
"'>" + Em.String.i18n('faq') + "</a>"
);
});
});

View File

@ -122,3 +122,14 @@ test("updateRelativeAge", function(){
equal($elem.html(), "2 mins ago");
});
test("breakUp", function(){
var b = function(s){ return Discourse.Formatter.breakUp(s,5); };
equal(b("hello"), "hello");
equal(b("helloworld"), "hello world");
equal(b("HeMans"), "He Mans");
equal(b("he_man"), "he_ man");
});