June 14th 2023

Merge Strings Alternately — Typescript

Problem Description permalink

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

Solution permalink

function expect(description: string, test: boolean) {
if (test) {
console.log(`${description}`)
} else {
console.log(`${description}`)
}
}

function mergeAlternately(word1: string, word2: string): string {
const lengthOfLongestWord = Math.max(word1.length, word2.length)
var result = "";

for (var i = 0; i < lengthOfLongestWord; i++) {
if (word1[i]) {
result = result + word1[i]
}
if (word2[i]) {
result = result + word2[i]
}
}

return result;
};

expect(`mergeAlternately("abc", "pqr") == "apbqcr"`, mergeAlternately("abc", "pqr") == "apbqcr")
expect(`mergeAlternately("ab", "pqrs") == "apbqrs"`, mergeAlternately("ab", "pqrs") == "apbqrs")
expect(`mergeAlternately("abcd", "pq") == "apbqcd"`, mergeAlternately("abcd", "pq") == "apbqcd")

Discussion permalink