Reputation: 181
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;
}
Upvotes: 4
Views: 603
Reputation: 10975
To achieve expected result, use below option
function getStringLength(arr){
return arr.lastIndexOf(arr.slice(-1))+1
}
var output = getStringLength('hello');
console.log(output);
https://codepen.io/nagasai/pen/gGPWEE?editors=1111
Option2: As type of array is object,below option works too
function getStringLength(arr){
return Object.keys(arr).pop()*1 + 1
}
var output = getStringLength('hello');
console.log(output);
https://codepen.io/nagasai/pen/PJZmgg?editors=1111
Check the below updated options to handle empty and numbers
https://codepen.io/nagasai/pen/GMoQgy?editors=1111
https://codepen.io/nagasai/pen/YrweWr?editors=1111
Upvotes: 1
Reputation: 506
Perhaps a slightly shorter answer:
function getStringLength(string) {
var counter = 0;
while (string.slice(counter)) {
counter++;
}
return counter;
}
var outputHello = getStringLength('hello');
console.log(outputHello); // 5
var outputEmpty = getStringLength('');
console.log(outputEmpty); // 0
Upvotes: 0
Reputation: 84982
The problem is the code substring.slice(counter)
First time, you chop off 1 character. Then you chop off 2 characters from the already-chopped substring. Either chop off 1 at a time, or chop off the increasing amount from the original string. So that's either substring.slice(1)
or string.slice(counter)
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);
Upvotes: 4
Reputation: 10458
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
Upvotes: 6