Let's assume that we are working with the following strings and we want to know if they can merge:
javascriptlet s1 = 'Hello'; let s2 = '__ll_'; let s3 = 'A____';
Cases:
s1
and s2
can merge (both have equal length and coincidence in chars)s1
and s3
can't merge ('H' and 'A' aren't equal).The goal is to create a function returning true
for the first case and false
for the second one.
javascriptconst stringsCanMerge = (stringA, stringB) => { // Declaring the function, we need to compare char to char let res = [...stringA].reduce( (acc, char, index) => { // Getting lengths of both strings let lengthA = stringA.length; let lengthB = stringB.length; // Getting current character let charA = stringA[index]; let charB = stringB[index]; // Conditions: // 1. String should have equal length // 2. Characters should be equal or one of two should be a '_' acc = acc && lengthA === lengthB && (charA === charB || charA === '_' || charB === '_'); // Returning accumulator return acc; }, true); return res; }
You could also translate the function in one line of code:
javascriptconst stringsCanMerge = (stringA, stringB) => [...stringA].reduce( (acc, char, i) => acc = acc && stringA.length === stringB.length && (stringA[i] === stringB[i] || stringA[i] === '_' || stringB[i] === '_'), true);
Let's test the function with some cases:
javascriptstringsCanMerge('Hello', '__ll_'); // true stringsCanMerge('Hello', 'A____'); // false stringsCanMerge('__ll_', 'A____'); // true
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.