How can I make the JavaScript more idiomatic?
By using indexOf
:
var containsA = function(sentence) {
return sentence.indexOf('A') != -1;
};
As your update specified that you want to use recursion, let's see what we can do.
Cleaning up, we can remove the else
(and the extraneous semi-colon).
var containsA = function(sentence) {
if (sentence.length === 0) {
return false;
}
return sentence[0] === 'A' || containsA(sentence.substr(1));
};
Or you can write it more succinctly, but I would say at the cost of readability
var containsA = function(sentence) {
return sentence.length > 0 &&
(sentence[0] === 'A' || containsA(sentence.substr(1)));
};
Now we could end up creating a lot of substrings. To avoid this, we can pass an index into the string
var containsA = function(sentence, i) {
i = i || 0;
if (i >= sentence.length) {
return false;
}
return sentence[i] === 'A' || containsA(sentence, i + 1);
};
Or
var containsA = function(sentence, i) {
i = i || 0;
return i < sentence.length &&
(sentence[i] === 'A' || containsA(sentence, i + 1));
}
In case this is not homework or a thought exercise...
Don't do this. By using recursion (and substr
) to solve this, you're simultaneously making your code less efficient, in terms of both time and memory, and less readable. As @Guffa pointed out, it may even blow the stack.
The function containsA
has no reason to exist. Just use indexOf
where appropriate.