JSFiddle - React, Tailwind, and code Playground

by Michael Spyratos

HTML

<div class="set">Set: <span></span></div>
<div class="string">String: <span></span></div>

CSS

span {
  color: blue;
}

JavaScript

const numberOfWordsToTest = 1000000;
const words = getWords();
const wordToFind = getWordSingle();

const timeExistsSet = getTime(existsSet);
const timeExistsString = getTime(existsString);

output('Set (ms)', '.set', timeExistsSet);
output('String (ms)', '.string', timeExistsString);

///////////////////////////////

function existsSet(str1, str2) {
  const set = new Set(str1);
  return ![...str2].some(char => !set.has(char));
}

function existsString(str1, str2) {
  return ![...str2].some(char => !str1.includes(char));
}

///////////////////////////////

function getTime(method) {
  const time = performance.now();
  words.forEach(word => method(word, wordToFind));
  return performance.now() - time;
}

function getWords() {
  let words = [];
  for (let i = 0; i < numberOfWordsToTest; i++) {
    words.push(getWordSingle());
  }
  return words;
}

function getWordSingle() {
  const charsAllowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let chars = [];

  for (var i = 0; i < 8; i++) {
    chars.push(charsAllowed.charAt(Math.floor(Math.random() * charsAllowed.length)));
  }

  return chars.join('');
}

function output(label, cls, time) {
  console.log(label, time);
  document.querySelector(`${cls} span`).textContent = (time / 1000).toFixed(6) + 's';
}