1
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Yes, I think you should use String.prototype.replace instead of array looping. I think so because .replace is probably going to be faster and because the code will be easier to understand.

I would also like to warn you about equality operator (===) in JavaScript. This returns false:

"ddd"===new String("ddd")

This returns true:

"ddd"==new String("ddd")

Also try to avoid if( !xxx ) with variables that are not supposed to be boolean, because it can get quite confusing for people reading your code.

Here's the callback replacement you talked about. You should use that and improve it so that it fits your exact definition if the conversion, which is missing in the question, so it wasn't addressed.

// -------- THE ACTUAL FUNCTION -------------------------

/* blah blah blah */
function dashedToCamelCase( dashed ) {
  if( typeof dashed != "string" || dashed.length==0 )
    return "";
  return dashed.toLowerCase().replace(/\-([a-z]?)/g, function(match, letter) {
      return letter.toUpperCase();
  });
}

// -------- 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',
               '',
               '' ];

var output = document.getElementById("output");
test.forEach(function(item, i) {
  try {
    var result = dashedToCamelCase(item);
    if(result==expect[i]) {
      writeOutput(item+" => "+result, "correct");
    }
    else {
      writeOutput(item+" => "+"got '"+result+"' instead of '"+expect[i]+"'", "wrong");
    }
  }
  catch(e) {
    writeOutput(e.message, "error");
  }
});
function writeOutput(text, className) {
  var p = document.createElement("p");
  p.appendChild(new Text(text));
  p.className = className;
  output.appendChild(p);
}
.correct {
  color: green;
}
.wrong {
  color: red;
}
.error {
  font-weight: bold;  
  color: red;
}
<pre id="output"></pre>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.