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 - a sn array of the chars tham make the MagicSequence in order.
* @return {object} - result with length of longest sequence and sequence itself
**/
function longestMagicSequence (s, chars) {

  var maxC = chars.length;

  var result = {
    length: 0,
    sequence: ''
  };
  var sequence = [[0, 0, '']];
  var count = 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][2];
      count = sequence[j][1];

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

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

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

          // if longest save in result
          count > result.length ? result = {length: count, sequence: 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.sequence.indexOf(chars[i]) === -1) {

      result = {length: 0, sequence: ''};
      break;

    }

  }

  // sequence holds all valid sequences if need to return all.
  // This function right now only needs the the...