function compoundMatch(words, target) {
const pairs = [];
for (let i = 1; i < target.length; i++) {
pairs.push([ target.slice(0, i), target.slice(i) ]);
}
for (const [ a, b ] of pairs) {
const ia = words.indexOf(a);
const ib = words.indexOf(b);
if (ia !== -1 && ib !== -1) {
return ia < ib ? [ a, b, [ ia, ib ] ] : [ b, a, [ ia, ib ] ];
}
}
return null;
}
или
function compoundMatch(words, target) {
const indices = {};
for (let i = 0; i < words.length; i++) {
const a = words[i];
if (!indices.hasOwnProperty(a)) {
indices[a] = i;
const b = target.replace(a, '');
if (indices.hasOwnProperty(b)) {
return [ b, a, a + b === target ? [ i, indices[b] ] : [ indices[b], i ] ];
}
}
}
return null;
}
или
function compoundMatch(words, target) {
const indices = {};
for (let i = 0; i < words.length; i++) {
indices[words[i]] = i;
}
for (const a in indices) {
for (const b in indices) {
if (a + b === target) {
return indices[a] < indices[b]
? [ a, b, [ indices[a], indices[b] ] ]
: [ b, a, [ indices[a], indices[b] ] ];
}
}
}
return null;
}