JSFiddle - React, Tailwind, and code Playground

by ainop

HTML

<input class="in" type="text" />
<div class="out"></div>

JavaScript

var base = [];

for (var i = 0; i < 10000; i++) {
	base.push((Math.round(Math.random() * 1e10)).toString(16));
}

(function (input, output, base) {
	input.focus();
	onInput();

	window.addEventListener('keydown', function (e) {
		input.focus();
	});

	input.addEventListener('input', debounce(onInput, 500));

	function onInput() {
		input.style.color = null;
		var out = search(input.value, base);
		if (out.length < 1) {
			input.style.color = 'red';
			output.innerHTML = 'Нет результатов для <b>' + input.value + '</b>';
		} else {
			output = replaceHtml(output, out.join('<br><br>'));
		}
	}

	function search(pattern, base) {
		var re = new RegExp(pattern, 'i');
		return base.map(function (entry) {
			if (re.test(entry)) {
                return entry.replace(/(?:\d{4} \d{2}-\d{3})(?: \d{1}-\d{2}-\d{2})?$/, '<b>$&</b>');
			}
		});
	}
}(
	document.querySelector('.in'),
	document.querySelector('.out'),
	base
));

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		clearTimeout(timeout);
		timeout = setTimeout(function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		}, wait);
		if (immediate && !timeout) func.apply(context, args);
	};
}

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
}