Created
July 24, 2014 21:39
-
-
Save yuchi/b017a592f647f50f8d35 to your computer and use it in GitHub Desktop.
CamelCaseUtil.normalizeCamelCase in JS
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
function isUpperCase(c) { | |
return (c !== c.toLowerCase()); | |
} | |
function normalize(s) { | |
var buffer = ''; | |
var upperCase = false; | |
var l = s.length; | |
var c, nextUpperCase; | |
for (var i = 0; i < s.length; ++i) { | |
c = s.charAt(i); | |
if (i < (l - 1)) { | |
nextUpperCase = isUpperCase(s.charAt(i + 1)); | |
} | |
if ((i > 0) && isUpperCase(c)) { | |
if (upperCase && nextUpperCase) { | |
c = c.toLowerCase(); | |
} | |
upperCase = true; | |
} | |
else { | |
upperCase = false; | |
} | |
buffer += c; | |
} | |
return buffer; | |
} | |
console.dir([ | |
'inputOVPs', | |
'inputOVPS', | |
'somethingURL', | |
'somethingURLs' | |
].reduce(function (memo, s) { | |
memo[ s ] = normalize(s); | |
return memo; | |
}, {})); | |
/* | |
outputs | |
{ inputOVPs: 'inputOvPs', | |
inputOVPS: 'inputOvps', | |
somethingURL: 'somethingUrl', | |
somethingURLs: 'somethingUrLs' } | |
*/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment