Is my layout of the if/else
statement reasonable?
It feels clumsy to me to spread the termination condition over the first three lines of the function. Can I squeeze it into one or two lines? Would it help if I used the ternary operator? How can I make the JavaScript more idiomatic (while still using recursion)? Any other improvements?
var containsA = function(sentence) {
if (sentence.length == 0) {
return false;
}
else {
return sentence[0] === 'A' || containsA(sentence.substr(1));
};
};
var containsA = function(sentence) {
if (sentence.length == 0) {
return false;
}
else {
return sentence[0] === 'A' || containsA(sentence.substr(1));
};
};
// Unit tests
var assert = function(code) {
if (eval(code)) {
document.write(code + " test passed.<br>");
}
else {
document.write(code + " test FAILED.<br>");
};
};
assert("!containsA('')");
assert("containsA('A')");
assert("!containsA('a')");
assert("containsA('HAH!')");
assert("!containsA('carrots')");
I have simplified details that are not relevant to my question. This simpler version attempts to reimplement String.prototype.contains()
. If I convert my string to an array I could use Array.prototype.find()
but my hunch is that would be less readable.
return false if sentence.length == 0
as a tidy way to put the termination condition in one line. Does Javascript offer a one-line equivalent to block-structured if? \$\endgroup\$if(sentence.length == 0) return false;
That's pretty much the only thing I can think of. (Right now, at least) \$\endgroup\$