Skip to content

Instantly share code, notes, and snippets.

@tooxie
Created September 14, 2013 09:42
Show Gist options
  • Save tooxie/6560574 to your computer and use it in GitHub Desktop.
Save tooxie/6560574 to your computer and use it in GitHub Desktop.
toCamelCase
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>toCamelCase</title>
<script src="tail-tocc.js"></script>
<script src="loop-tocc.js"></script>
<script type="text/javascript">
var camelCaseMe = 'string-with-some-dashes';
function time(fn) {
var start = new Date().getTime();
var i = 1000000;
while(i--) {
fn();
}
console.log("Milliseconds: " + (new Date().getTime() - start));
}
time(function() {
TAIL.toCamelCase(camelCaseMe);
});
time(function() {
LOOP.toCamelCase(camelCaseMe);
});
</script>
</head>
<body>
</body>
</html>
/* While loop toCamelCase */
var LOOP = {
toCamelCase: function(s) {
var i = s.indexOf('-');
function capitalize(s) {
return s[0].toUpperCase() + s.substr(1);
}
while(i > -1) {
s = s.substr(0, i) + capitalize(s.substr(i + 1))
i = s.indexOf('-');
}
return s;
}
}
/* Tail recursion toCamelCase */
var TAIL = {
toCamelCase: function(s) {
var i = s.indexOf('-');
if (s === '' || i === -1) {
return s;
}
function capitalize(s) {
return s[0].toUpperCase() + s.substr(1);
}
return s.substr(0, i) + this.toCamelCase(capitalize(s.substr(i + 1)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment