JSFiddle - React, Tailwind, and code Playground
by dpren
HTML
<h4>Output:</h4>
<div id="logDiv"></div>
JavaScript
/*------ Helpers: ------*/
const logDiv = document.getElementById('logDiv');
const log = msg =>
logDiv.insertAdjacentHTML('beforeend', `<div>${msg}</div>`);
const stringToArray = a =>
a.split('');
// return first arg if value exists, else return second arg.
const ifDefinedElse = (val, elseVal) =>
(val !== undefined && val !== null)
? val
: elseVal;
/*------ Merge definition: ------*/
// Maps A to a concatenation of B at the same index.
// If B's length runs out, concat empty string in place of undefined.
const arrayMerge = (aArray, bArray) =>
aArray.map(
(a, i) => a + ifDefinedElse(bArray[i], '')
);
// If B was longer, this just flips the args and concatenation order so it's not cut off.
const arrayMergeFlippedConcat = (bArray, aArray) =>
aArray.map(
(a, i) => ifDefinedElse(bArray[i], '') + a
);
// Applies the appriopriate merge function to the string arguments, which are converted to arrays and back.
// With better langugae/tooling, you could just map strings directly.
const merge = (aStr, bStr) => {
const mergeFn =
aStr.length >= bStr.length
? arrayMerge
: arrayMergeFlippedConcat;
return (
mergeFn(
stringToArray(aStr),
stringToArray(bStr)
).join('')
);
};
/*------ Output: ------*/
log(merge('abc', '123'));
log(merge('abc', '123456'));
log(merge('abcdef', '123'));
log(merge('', ''));