I have to write a function which turns a string with the words separated by dashes ( - ) into a sentence using camel case notation.
I've had the following idea for an implemenation using the reduce-method of Array:
// -------- THE ACTUAL FUNCTION -------------------------
/**
* Converts a string with dashes as word-separators
* to a string using camel case notation.
* --------------------------------------------------
* @param {String} Sentence-string with dashes (-)
* as word-separators.
*
* @returns {String} Sentence-string in Camel Case
* notation.
* Returns an empty string as an indicator of failure.
* ---------------------------------------------------
* Usage-Example:
* dashedToCamelCase('north-east-east') // Returns 'northEastEast'
*/
function dashedToCamelCase( dashed ) {
var ret;
var parts;
if (typeof dashed !== 'string' || !dashed) {
return '';
}
parts = dashed.split('-');
ret = parts[0].toLowerCase();
parts = parts.slice(1);
ret = parts.reduce(function(previous, current) {
return previous +
current.slice(0, 1).toUpperCase() +
current.slice(1).toLowerCase();
}, ret);
return ret;
}
// -------- THE ACTUAL FUNCTION - END -------------------
// --- TESTING ---------------------------
var test = [ 'north',
'north-east',
'north-east-east',
'south-west-west-north',
'south-wEst-EaSt',
'North-west-EAST',
'NORTH-EAST-SOUTH-WEST',
248,
'' ];
var expect = [ 'north',
'northEast',
'northEastEast',
'southWestWestNorth',
'southWestEast',
'northWestEast',
'northEastSouthWest',
'',
'' ];
test.forEach(function(item, i) {
dashedToCamelCase(item) === expect[i]
? console.log('%s passed.', i)
: console.error('%s FAILED!', i);
});
I have seen similar functions which use the replace-method of String together with a function as a parameter. Still not convinced if I should keep with my solution ...
So: Should I use an implementation using String.replace? Or are just some improvements needed?
I would like to try it out with a large amount of automatically created data.
Does someone know a good way for measuring the performance?