Am trying to get a string length using recursion but couldn't get it can anyone help.
thank you
The basic idea of recursion is calling itself inside the function.
function strLen(str,cnt) {
cnt = cnt || 0;
if (str.length) {
return strLen(str.substr(1), ++cnt);
} else {
return cnt;
}
}
console.log(strLen("asdf"));
console.log(strLen("1234567890"));
If you want to do it the trampoline way you were tyring, it is basically the same thing, just returning a function instead of calling it.
function trampoline(f) {
while(f && typeof f === "function") {
f = f();
}
return f;
}
function strLen(str, cnt) {
cnt = cnt || 0;
if (str.length) {
return strLen.bind(this, str.substr(1), ++cnt);
} else {
return cnt;
}
}
console.log(trampoline(strLen("TEST")));
console.log(trampoline(strLen.bind(null, "1234567890")))
const strLen = str => str == '' ? 0 : strLen(str.substring(1)) + 1;
So for strLen('apple')
:
So, the program sums 1 + 1 + 1 + 1 + 1 + 0 = 5.
To be more precise, with recursive functions, the last function called returns first; the process would actually look more like this:
Basically, 1 is added to the result of the base case (the final return, 0) as many times as it took to arrive at the base case, or:
0 ->
(1 + 0) ->
1 + (1 + 0 ) ->
1 + (1 + (1 + 0)) ->
1 + (1 + (1+(1 + 0))) ->
1 + (1 + (1 + (1 + (1 + 0)))) = 5
Perhaps something like this?
strLength = 0;
for (var i = 0; i < string.length; i++){
strLength++;
}
EDIT:
Here is a new solution I thought of:
function stringLength(string)
parts = string.split("");
stringLength = 0;
for (x in parts){
stringLength++;
}
console.log(stringLength("Hello"))
EDIT #2:
After running your code, I realize the issue. The function you gave me runs once for each length of the string, meaning that the call stack fills up with all the function calls. This link explains more: Maximum call stack size exceeded error
The function I provided above handles strings of over a million characters well. Javascript really is limited by the browser, so performance above a certain length will be greatly limited by restrictions the browser places on executed code.
In short, the way you want to do it will never work on strings that are any longer than a few dozen characters. My way, while probably not the most performant, will work on strings with lengths of upwards of a million with no problem.
Here is a JSBin: https://jsbin.com/josuqekeli/edit?html,js,output