How to merge two strings based on shared suffix and prefix in TypeScript

1 Answer

0 votes
function mergeOnOverlap(a: string, b: string): string {
    const lenA = a.length;
    const lenB = b.length;

    const maxPossibleOverlapLen = Math.min(lenA, lenB);

    let overlap = 0;

    for (let len = maxPossibleOverlapLen; len > 0; len--) {
        if (a.slice(lenA - len) === b.slice(0, len)) {
            overlap = len;
            break;
        }
    }

    return a + b.slice(overlap);
}

const a = "fantasy time travel technology";
const b = "technology extraterrestrial life";

console.log(mergeOnOverlap(a, b));


 
 
/*
run:
 
"fantasy time travel technology extraterrestrial life"
 
*/

 



answered Jan 24 by avibootz
...