Created
March 28, 2017 15:46
-
-
Save alexdemers/4a363ad90a58b4e3193f5dc5ff105f5d to your computer and use it in GitHub Desktop.
Laravel's pluralization logic in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// replace occurences of :vars in the string. | |
// "This :thing is great!".format | |
String.prototype.format = function(replacements) { | |
var str = this; | |
for (var key in replacements) { | |
if (replacements.hasOwnProperty(key)) { | |
str = str.replace(':' + key, replacements[key]); | |
} | |
} | |
return str; | |
}; | |
// Adds the ability to pluralize strings using Laravel's pluralization engine | |
// "{0} No files selected|{1} 1 file selected|[2,Inf] :count files selected".pluralize(4, { count : 4 }) | |
String.prototype.pluralize = function(number, replacements) { | |
var terms = this.split('|'); | |
var regex = /^\s*({[0-9]+}|\[[0-9]+,Inf])\s*(.*)$/g; | |
var matches; | |
for (var i in terms) { | |
if (!terms.hasOwnProperty(i)) { | |
continue; | |
} | |
var term = terms[i]; | |
while ((matches = regex.exec(term)) !== null) { | |
// This is necessary to avoid infinite loops with zero-width matches | |
if (matches.index === regex.lastIndex) { | |
regex.lastIndex++; | |
} | |
var isTheOne = false; | |
var str = ''; | |
for (var groupIndex in matches) { | |
if (!matches.hasOwnProperty(groupIndex)) { | |
continue; | |
} | |
if (groupIndex === "2" && isTheOne) { | |
str = matches[groupIndex]; | |
} | |
if (groupIndex !== "1") { | |
continue; | |
} | |
var match = matches[groupIndex].substring(1, matches[groupIndex].length - 1).toLowerCase(); | |
if (match.indexOf(',') >= 0) { | |
var between = match.split(','); | |
var start = between[0] === '-inf' ? Number.MIN_VALUE : between[0]; | |
var end = between[1] === 'inf' ? Number.MAX_VALUE : between[1]; | |
if (number >= start && number <= end) { | |
isTheOne = true; | |
} | |
} else if (parseInt(match) === number) { | |
isTheOne = true; | |
} | |
} | |
if (isTheOne) { | |
return str.get(replacements); | |
} | |
} | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice :-)
Do you have a version that does not use the String prototype?
Just as a normal method?