Skip to content

Instantly share code, notes, and snippets.

@ridoansaleh
Last active December 6, 2019 02:54
Show Gist options
  • Save ridoansaleh/a988e12edcddb44d8746d09ab35ad436 to your computer and use it in GitHub Desktop.
Save ridoansaleh/a988e12edcddb44d8746d09ab35ad436 to your computer and use it in GitHub Desktop.

Select Search

Options with "No Match"

const options = [
  {
    val: "Messi",
    desc: "Forward"
  },
  {
    val: "Toni Kroos",
    desc: "Playmaker"
  },
  {
    val: "van Dijk",
    desc: "Defender"
  },
  {
    val: "De Gea",
    desc: "GoalKeeper"
  }
]

Options with "One Match"

Result: ss

const options = [
  {
    val: "Messi",
    desc: "Forward"
  },
  {
    val: "Toni Kroos",
    desc: "Playmaker"
  },
  {
    val: "van Dijk",
    desc: "Defender"
  },
  {
    val: "Alisson",
    desc: "GoalKeeper"
  }
]

Options with "Multiple Match in One Word"

Result: an

const options = [
  {
    val: "Stefano Andalan",
    desc: "Forward"
  },
  {
    val: "Anda anti",
    desc: "Playmaker"
  },
  {
    val: "Siapa Anda",
    desc: "Defender"
  },
  {
    val: "Mignolet",
    desc: "GoalKeeper"
  }
]

Function to Generate Bold List

function generateListItem(word = "Stefano Andalan", input = "anda") {
  if (input.length < 2) { return; }
  //let input = "anda";
  let _input = input.toLowerCase();

  //let word = "Stefano Andalan";  //=> [Andalan Stefano, andalan stefANo] / possibilities

  let firstIndexFound = word.toLowerCase().indexOf(_input) // 8
  
  if (firstIndexFound < 0) { return; }

  let arr1 = word.split(""); //=> [S, t, e, f, a, n, o, A, n, d, a, l, a, n];
  let arr2 = word.split(""); //=> [S, t, e, f, a, n, o, A, n, d, a, l, a, n];
  
  let searchText = [];
  arr1.forEach((item, index) => {
    if (index >= firstIndexFound && (_input.indexOf(item.toLowerCase()) > -1) && (searchText.length < input.length)) {
      searchText.push(item);
    }
  })

  let puzzle1 = arr1.splice(0, firstIndexFound); // (0, 4) => return element from index 0 to first letters matched
  let puzzle2 = arr2.splice(firstIndexFound + input.length); // (4+2) => return the rest of the array from index of firstIndexFound + input length 
  
  // let result = `${puzzle1}<b>${searchText.join("")}</b>${puzzle2}`; // => for React
  
  let result = `${puzzle1.join("")}${searchText.join("")}${puzzle2.join("")}`;

  return result;
}

Test Cases

No Input Word Result Status Format Test
1 an Stefano Andalan Stefano Andalan OK Stefano Andalan => Multiple matched
2 Anda Stefano Andalan Stefano Andalan OK Stefano Andalan => There is an before Anda piece of word
3 Bu Budiman Budiman OK Budiman - One matched in front
4 an Budiman Budiman OK Budiman - One matched in the back
5 i Budiman undefined OK Budiman - Found, but only one letter
6 dd Budiman undefined OK Not found - 2 letters
7 4 Budiman undefined OK Not found - number

Demo

You can check the demo here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment