JSFiddle - React, Tailwind, and code Playground

by Andrey Aires

HTML

<input type="search" id="search-input"/>
<div id="predictions"></div>

JavaScript

(function() {
  'use strict';
  var MAX_PREDICTIONS_COUNT = 5,
    dictionary = [{
      word: 'abba',
      weight: 100
    }, {
      word: 'abcd',
      weight: 90
    }, {
      word: 'abfe',
      weight: 80
    }, {
      word: 'abbb',
      weight: 110
    }, {
      word: 'abcf',
      weight: 70
    }, {
      word: 'abcg',
      weight: 120
    }, {
      word: 'accg',
      weight: 120
    }, {
      word: 'adcg',
      weight: 120
    }],
    map = {},
    searchInputElement,
    predictionsElement;

  function attachListeners() {
    searchInputElement = document.getElementById('search-input');
    predictionsElement = document.getElementById('predictions');

    searchInputElement.addEventListener('keyup', function(event) {
      var value = event.target.value,
        predictions = predict(value) || [];
      predictionsElement.innerHTML = predictions.join('<br>');
    });
  };

  function buildMap() {
    var item,
      pathArray;

    for (var i = 0; i < dictionary.length; i++) {
      item = dictionary[i];
      pathArray = item.word.split('');

      addItemToMap(map, pathArray, item.weight, i);
    };
  };

  function addItemToMap(mapNode, pathArray, weight, index) {
    var letter;

    if (pathArray && pathArray.length) {
      letter = pathArray.shift();

      if (mapNode[letter]) {
        managePredictions(mapNode[letter].predictions, index);
      } else {
        mapNode[letter] = {
          predictions: [index],
          children: {}
        }
      }
      addItemToMap(mapNode[letter].children, pathArray, weight, index);
    }
  };

  function managePredictions(predictions, index) {
    var insertionIndex = getInsertionIndex(predictions, index);

    predictions.splice(insertionIndex, 0, index);
    if (predictions.length > MAX_PREDICTIONS_COUNT) {
      predictions = predictions.splice(-1, 1);
    }
  };

  function getInsertionIndex(array, index) {
    var low = 0,
      high = array.length,
      middle;

    while (low < high)...