JSFiddle - React, Tailwind, and code Playground

by ronilan

JavaScript

/**
* ShareThis Hiring Question from the HackerRank Test:
*
* Yaron (Ron) Ilan <[email protected]>
* Fabriqué au Canada : Made in Canada
**/

/**
* longestMagicSequence - finds the longest sequence of specific chars (with repetitions) in a string.
*
* @param {string} s - a string
* @param {array} chars - an array of the chars that make the MagicSequence. In order.
* @return {string} - the longest sequence itself.
**/
function longestMagicSequence (s, chars) {

  var maxC = chars.length;

  var result = '';
  var sequence = [[0, '']];
  var str = '';

  var i,
      j,
      k,
      max,
      maxS;

  // must contain all chars at least once
  for (i = 0; i < maxC; i++) {

    if (s.indexOf(chars[i]) === -1) {

      s = '';
      break;

    }

  }

  // remove all left of first a
  s = s.substring(s.indexOf(chars[0]));

  // remove all right of last u
  s = s.substring(0, s.lastIndexOf(chars[chars.length - 1]) + 1);

  max = s.length;

  // for each letter
  for (k = 0; k < maxC; k++) {

    // for each stored sequence
    maxS = sequence.length;
    for (j = 0; j < maxS; j++) {

      str = sequence[j][1];

      // strat from end of last sequence
      for (i = sequence[j][0]; i < max; i++) {

        if (s.substr(i, 1) === chars[k]) {

          str = str + s.substr(i, 1);
          sequence.push([i, str]);

          // if longest save in result
          str.length > result.length ? result = str : null;

        }

      }

    }

    // get rid of unused
    sequence.splice(0, maxS);

  }

  // result must contain all chars at least once
  for (i = 0; i < maxC; i++) {

    if (result.indexOf(chars[i]) === -1) {

      result = '';
      break;

    }

  }

  // sequence now holds all valid sequences (if need to return all).
  // This function (right now) only needs the the longest one.
  return result;

}

/** Tests
* A set of test cases for longestMagicSequence.
* Note, you may use factory functions to generate test cases.
**/

// function being tested
var...