What'w wrong with my code?

I am trying to create the .words() method. It is supposed to split a sentence into an array of strings. It does this by identifying where there is a space character in the array and splitting up words at this point. Please note I initially did not want to use the .split() method. Why does the current code I have written not work? I do not even genuinely understand what happens when I run the code.

const _ = {
    clamp(ein, lower, upper){
        let zwe = Math.max(ein, lower);
        let dre = Math.min(zwe, upper);
        return dre;
    },

    inRange(ers, start, end){
        if (!end){
          end = start;
          start = 0;
        }else if (end < start){
          let tmp = end;
          end = start;
          start = tmp;
        }
        (ers <= start && ers < end)? true : false;
      },

        words(string){
        let wordArray = [];
        let ers = 0;
        let zwe = string.indexOf(' ', ers);
        while(zwe <= string.length){
            let word = string.slice(ers, zwe);
            wordArray.push(word);
            ers += zwe + 1;
            zwe += string.indexOf(' ', ers);
        }
        return wordArray;
    }
}

console.log(_.words('this should please work'));



// Do not write or modify code below this line.
module.exports = _;

Is there a particular reason you don’t want to use .split() ? because it would mean the solution is:

word(string){
  return string.split(" ");
}

If you really, really want to avoid using .split(), check this repl I made. I hope it helps!
REPL.IT LINK

Oh, and if you want to know why your code is breaking, think about your loop step by step! using console.log() in this cases is very helpful.

Iteration 1:
   ers = 0, zwe = 4, word = 'this', ers = 5, zwe = 11
Iteration 2:
   ers = 5, zwe = 11, word = 'should', ers = 12, zwe = 18
Iteration 3:
   ers = 12, zwe = 18, word = 'please', ers = 19, zwe = -1

[... infinite loop...]

Your logic of using string.indexOf(' ', ers); does not work for the last word. When you ask .indexOf() to find a whitespace from index 19 onwards, it finds none and returns -1. At this point your logic breaks and the while loop will continue indefinitely.

Thank you. That was really helpful. I did not want to use split just because they used this in their own solution and I was trying to find another solution that would also create the same functionality.

1 Like