Q
Q
Quintis2020-05-08 18:50:48
JavaScript
Quintis, 2020-05-08 18:50:48

How to optimize the code?

Good day, I solved a small problem on codewars - https://www.codewars.com/kata/5aaae0f5fd8c069e8c00... but the solution is not correct because not all tests pass in 12000 ms: "If you see this error multiple times you should try to optimize your code further."How to optimize it ?

function compoundMatch(words, target) {
  let result = null
  let i,index,firstWord,secondWord
  let arrWordsLength = words.length

marck:for(i=0;i<arrWordsLength;i++) {
      index = words[i].length
      firstWord = target.slice(0,index)
      secondWord =target.slice(index) 
      let firstWordIndex = words.indexOf(firstWord)
      let secondWordIndex = words.indexOf(secondWord)
      if (words[i] === firstWord && firstWordIndex>=0 && secondWordIndex >=0 ){
      let firstWordInArr = Math.min(firstWordIndex,secondWordIndex)
      let secondWordInArr = Math.max(firstWordIndex,secondWordIndex)
      console.log(firstWordInArr,secondWordInArr)
      result=[words[firstWordInArr],words[secondWordInArr],[firstWordIndex,secondWordIndex]]
      break marck
      }

};
return result
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-05-08
@Quintis

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;
}

or
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;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question