Jeremy Odell Jeremy Odell - 1 year ago 139
Javascript Question

Using reduce() in defining new string methods

I am having trouble re-factoring my solution to the "Jaden Casing Strings" kata on codewars. The problem is to capitalize the first letter of every word of a given sentence, like this:

Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"

Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"

Here is my solution:

function jayden (sen) {
sen = sen.split('').reduce(function (str, next, ind) {
return str + (!sen[ind - 1] || sen[ind - 1] === ' ' ? next.toUpperCase() : next);
}, '');
return sen

String.prototype.toJadenCase = function () {
return jayden(this)

Ideally I would like to have the contents of the
function inside of
String.prototype.toJadenCase = function () {
but I can't seem to iterate through
. Is it possible to iterate through

Answer Source

Here's how you could do it, in a more simple way:

String.prototype.toJadenCase = function () {
    return this.split(" ").map(function(x){
       return x[0].toUpperCase()+x.slice(1);
    }).join(" ");
console.log("How can mirrors be real if our eyes aren't real".toJadenCase())

Another example using reduce():

String.prototype.toJadenCase = function () {
  return this.split('').reduce(function (str, next, index) {
    return str+(str[index-1]==" "?next.toUpperCase():next)        
console.log("How can mirrors be real if our eyes aren't real".toJadenCase())

How does the second example work:

Each time str is the current part of string without a last char. The last char is next. Here's the breakdown, how str and next change with each iteration. Before the comma is str, after is next.

    How ,c
    How C,a
    How Ca,n
    How Can, 
    How Can ,m
    How Can M,i
    How Can Mi,r
    How Can Mir,r
    How Can Mirr,o
    How Can Mirro,r
    How Can Mirror,s
    How Can Mirrors, 
    How Can Mirrors ,b
    How Can Mirrors B,e
    How Can Mirrors Be, 

The logic is: return str+next, if str doesn't end with a space (i.e. str[index-1], which is the last char, is a space). If str ends with a space, then next is a the first letter of new string. Then it's capitalized. So, in this case we're returning str+next.toUpperCase()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download