1

Here's a tough question which I'm unable to solve.

Write a recursive function that accepts a string and returns its length. Do not use the .length property, loops, or any built-in methods in Javascript to find the solution.

I'm quite close with this solution but I'm not able to find an alternative to the .slice() method. This function currently works but doesn't fit the question's parameters because if uses that method, and the .length property:

let lengthGetter = (str, def) => {
  let len = def || 0;
  if (str[0] === undefined) return len;
  return lengthGetter(str.slice(0, str.length - 1), len + 1);
};

console.log(lengthGetter("hello")) // 5

Even if it involves throwing away my current function, can anyone find a solution to this problem? Keep in mind you can't use any built-in methods or loops, which makes it quite challenging.

1
  • 2
    You can check for the presence of a character with simplly str[n]; if that's undefined it means you're beyond the end of the string (or before the start). Commented Mar 26, 2021 at 16:10

3 Answers 3

4

This is the easiest recursive one-liner you can make to get the length of the given string without using any built-in methods.

const getLength = (str = "", length = 0) => str[length] ? getLength(str, length + 1) : length;

Sample:

const getLength = (str = "", length = 0) => str[length] ? getLength(str, length + 1) : length;

console.log(getLength("hello"))
console.log(getLength("helloworld"))

Sign up to request clarification or add additional context in comments.

2 Comments

Well, using the fact that strings are iterable, this might be even easier: const len = ([s, ...ss]) => s == undefined ? 0 : 1 + len (ss)
That's more neat.
2

Close to what you have written:

let lengthGetter = (str, pos = 0) => {
  if (str[pos] === undefined) return 0;
  return 1 + lengthGetter(str, pos + 1);
};

Comments

2

This often comes as a surprise:

'🌯🌯🌯'.length
//=> 6

If you need to count what humans would see then you can destructure the string as most (but not all) characters would be preserved as such:

[...'🌯🌯🌯'].length
//=> 3

So we can have:

const Nil = Symbol();
const len = ([x = Nil, ...xs]) => x === Nil ? 0 : 1 + len(xs);

len('foo');
//=> 3
len('🌯🌯🌯');
//=> 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.