I am doing a very simple coding challenge. Return every nth letter of string. And, before this gets marked as duplicate, I already have a few solutions. And, I know with programming there are probably many ways to achieve the same result. But I was wondering if there is any great difference in terms of logic, readability, or just syntax in general for the following solutions. Which would be considered the favorable solution? In this example I am doing every three. If you have a better solution I would like to see.

function testcode(str){
  let newstr = '';
  for (let i=2; i<str.length; i+=3) {
      newstr += str[i]
  }
  return newstr;
}
testcode('hellostackoverflow');

function testcode(str){
  let newstr='';
  for (let i=0; i<str.length; i++) {
      if ((i+1)%3 === 0){
        newstr += str[i];
      }
  }
  return newstr;
}

testcode('hellostackoverflow');

I tried a regex way as well, but it's not replacing the characters if there aren't exactly 3.

let str = "aaCaaCaaCaa";

let result = str.replace(/..(.)/g, "$1");
console.log(result);
//gives me CCCaa

1 Answers

0
Bergi On Best Solutions

Which would be considered the favourable solution?

Your first one. It is simple, both logically and syntactically, leading to high readability.

And possibly more important, it is also more efficient: it takes only O(n/k) steps (where k=3 in your example), looking only at every third index/character instead of every single one (O(n)).