Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Get Length of a String without Length Propery, And with Slice

Tags:

javascript

I know, it's a weird one! But why does this not work?

function getStringLength(string) {

  // see how many substrings > 0 can be built
  // log that number & return

  var subString = string.slice();
  var counter = 0;

  while (subString !== '') {
    counter++;
    subString = subString.slice(counter);
  }

  return counter;
}

var output = getStringLength('hello');

console.log(output); // --> expecting 5, but getting 3 (??)

I really want to do it with slice! The original challenge was to not use the length property, and I figured this out, which works fine:

function getStringLength(string) {

  var long = 0;

  while (string[long] !== undefined) {
    long++;
  }

  return long;
}
like image 494
marie_antoinette Avatar asked Dec 18 '22 04:12

marie_antoinette


1 Answers

you were mutating your string, this should work for you

function getStringLength(string) {

  // see how many substrings > 0 can be built
  // log that number & return

  var subString = string.slice();
  var counter = 0;

  while (subString !== '') {
    counter++;
    subString = subString.slice(1);
  }

  return counter;
}

var output = getStringLength('hello');

console.log(output); // 5

The main difference was that I was doing

subString = subString.slice(1);

instead of

subString = subString.slice(counter);

which always decreased length by 1

like image 159
marvel308 Avatar answered Dec 24 '22 02:12

marvel308