Hoping to learn better ways to solve this algorithm. The input consists of two strings.
Input - example 1:
var a = 'abc'
var b = 'def'
Expected Output
mergedString = 'adbecf';
My solution:
var a = 'abc';
var b = 'efg';
function mergeStr(a, b) {
var aArr = a.split('');
var bArr = b.split('');
var newStr = '';
for (var i = 0; i < aArr.length; i++) {
newStr += aArr[i] + bArr[i];
}
}
mergeStr(a, b);
The solution works for the input example above. But I was stuck when the second input values were given to me which is:
var a = 'ab';
var b = 'efg';
The expected output is:
aebfg
LOL since I was being timed I came up with the following junk. I just added an if statement to deal with the exact use case I was given. Obviously this solution is junk. I would really like to see what others would do.
function mergeStr(a, b) {
var aArr = a.split('');
var bArr = b.split('');
var newStr = '';
for (var i = 0; i < aArr.length; i++) {
newStr += aArr[i] + bArr[i];
}
if (a.length < b.length) {
newStr += b[2];
}
console.log(newStr);
}