heliu heliu - 9 months ago 54
Javascript Question

How can I rewrite the .length() property using slice()?

This is my assignment:

By now you should have worked with the length property of strings, e.g. "hello".length. Your task is to write a function called stringLength that accepts a string as a parameter and computes the length of that string; however, as you may have guessed, you are not allowed to use the length property of the string!

Instead, you'll need to make use of the string method called slice.
For our purposes, we can consider slice as taking one argument -- the index to begin slicing from, and returns a new string starting from that index onwards.

This is what I tried:

function stringLength(string){
var count = count++;
return count}
return stringLength(string.slice(0,-1))

I am trying to slice each character of the string back to start index, index 0, and then accumulate my count variable. I do not understand why my count variable is not accumulating.

Answer Source

Hmm i tried to write code in the same format that you did.

function stringLength(str, count){
     return count;
    return  stringLength(str.slice(0,-1), ++count) 
console.log(stringLength("game", 0))

I'll point out the mistakes in your original code so that its easy to understand.

  1. The recursion base case was incorrect. string.slice(0) will return true if the string is non-empty, so use !string.slice(0)

  2. The count value was not initialized and it wasn't being passed down the recursion.