No need to use abbreviation when you can use meaningful name. For example, use result
instead of res
.
Also if you can find a better name for your function, it will improve the readability. I will use alternateLetters
but I think we can do better :)
To achieve your problem, you can use a for loop or a generate a range then use map
to assign the letter.
function alternateLetters(num) {
const a = 'A', b = 'B';
const result = [...Array(num)].map((_, i) => i % 2 ? b : a);
console.log(result.join(''))
}
alternateLetters(5) // return "ABABA"
if you prefer, you can also generate result
with keys()
:
const result = [...Array(num).keys()].map(i => i % 2 ? b : a);
By the way I would make it more generic by passing 'A' and 'B' as parameter:
function alternateLetters(num, a, b) {
const result = [...Array(num)].map((_, i) => i % 2 ? b : a);
return result.join('');
}
console.log(alternateLetters(5, 'A', 'B')) // return "ABABA"
If we have more context about this problem, we may even do better. For example, are "A" and "B" always constant?