[JS] Convert dash-separated string to camelCased using reduce

It's very common in JS to name files using dash-separated string, and functions using camel case. In fact, many libraries use this rules to automatically discover files. Hence, a function to convert dash-separated string to camelCase is of great use. There are, certainly, many ways to implement this function. I just want to show here one way to it using reduce function.

Just in case you didn't know about reduce function, it executes a call back function once for each element of a collection and store the result in an accumulator, which is the first argument of the callback function. The last argument of reduce function is the inital value of the accumulator. Although, ES standard only supports reducing on Array, lodash library allows you to apply it on objects as well. Following is the syntax of reduce.

arr.reduce(function(accumulator, item) {
    /* callback function body */

For more information on reduce, you can read this MDN doc and lodash doc.So, here is how you can convert dash-separated string to camcelCased using reduce.

function camelCase(dashedString) {
  return dashedString.split('-')
    .reduce(function(result, word) {
      return result + word[0].toUpperCase() + word.slice(1);

Note that initialValue value is optional. If you want to capitalize the very first letter of the string, set the initialValue to and empty string ''.

No comments:

Post a Comment