F
F
Finch_852018-05-27 06:32:31
JavaScript
Finch_85, 2018-05-27 06:32:31

How can these features be improved?

Hello. In order to understand the work with strings (there were some gaps), I wrote a couple of functions. But it seems to me that the code is cumbersome and it can be improved significantly. Advise, criticize, point out mistakes.
So, you need to write a method that finds all the positions of the occurrence of a substring in a string. I did it in 3 ways, one - I spied.

function findAll(str, target) {
  let res = [];
  for(let position = 0; position < str.length; position++) {
    if(str.toLowerCase().indexOf(target.toLowerCase(), position) !==-1) {
      position = str.indexOf(target, position);
      res.push(str.indexOf(target, position));
    }
  }
  return res
}

function findAllTwo(str, target) {
  let position = 0,
     result = [];
  while (true) {
    if (str.indexOf(target, position) ==-1) break;
    result.push(str.indexOf(target, position));
    position = str.indexOf(target, position)+1;
  } 
  return result;
}

function findAllThree(str, target) {
  let regexp = new RegExp(''+target+'', 'g');
  let res = [];
  while (result = regexp.exec(str)) {
    res.push(result.index)
  }
  return res
}

// возвращает массив с позициями вхождения [10, 22, 46]
console.log( findAll('i have an apple, some appricots and fantastic apps', 'app') )
console.log( findAllTwo('i have an apple, some appricots and fantastic apps', 'app') )
console.log( findAllThree('i have an apple, some appricots and fantastic apps', 'app') )

The third seems to me the best, but how to improve the 2 previous ones?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-05-27
@Finch_85

In the first example, you can slightly optimize the running time due to fewer indexof calls:

function findAll(str, target) {
  let res = [];
  let ind = 0;
  for(let position = 0; position < str.length; position++) {
     if (ind <= position){
         ind = str.indexOf(target, position);
         if (ind == -1) break;
         res.push(ind);
     }
  }
  return res
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question