DEV Community

Discussion on: Breaking Down JavaScript Solutions To Common Algorithmic Questions (Part 1)

Collapse
 
0x450x6c profile image
El Azimov
function reverse(str) {
  return _reverse(str.matchAll(/./gu));
}

function _reverse(lettersIter) {
  const { value, done } = lettersIter.next();
  if (done) {
    return '';
  }

  return _reverse(lettersIter) + value[0];
}

image


function findLongestWordLength(str) {
  const wordsIter = str.matchAll(/[^ ]+/gu);

  return _findLongestWordLength(wordsIter);
}

function _findLongestWordLength(wordsIter) {
  const { value, done } = wordsIter.next();

  if (done) {
    return 0;
  }

  return Math.max(value[0].match(/./gu).length, _findLongestWordLength(wordsIter));
}

image

function largest(arr) {
  return arr.map(it => maximum(it[Symbol.iterator]()));
}

function max(a, b) {
   return a >= b ? a : b;
}

function maximum(iter) {
   const { value, done } = iter.next();
   if (done) {
     return 0;
   }

   return max(value, maximum(iter));
}

image