Split String into array on phrase

Benchmark created on


Setup

const testStr = 'if foo === bar, then would bar === foo.  Yes, bar would equal foo';

Test runner

Ready to run.

Testing in
TestOps/sec
Recursive
const fragmented = [];

function getIndex(phrase, text) {
  const lowerText = text.toLowerCase();
  const lowerPhrase = phrase.toLowerCase();
 
  return lowerText.indexOf(lowerPhrase);
}

function recursive(phrase, text) {
   const index = getIndex(phrase, text);
   console.log('index', index);
   if(index < 0) {
   	  fragmented.push(text);
   	  return fragmented;
   } 
   fragmented.push(text.slice(0, index));
   fragmented.push(text.slice(index, index + phrase.length));
   const after = text.slice(index + phrase.length);
  return recursive(phrase, after);
}

recursive('Foo', testStr)
ready
generator
function* indexesOfPhrase(text, phrase) {
  let i = 0;
  while (true) {
    const r = text.indexOf(phrase, i);
    if (r !== -1) {
      const start = i === 0 ? 0 : i + phrase.length;
      yield text.slice(start, r - 1);
      yield text.slice(r, r + phrase.length);
      i = r + 1;
    } else return;
  }
}

[...indexesOfPhrase(testStr, 'Foo')]
ready
split
function splitByPhrase(phrase, text) {
  const lowerText = text.toLowerCase();
  return lowerText.split(phrase.toLowerCase()).reduce((acc, subStr)=>{
    const startIndex = lowerText.indexOf(subStr);
    const endIndex = startIndex + subStr.length;
    if (startIndex === -1 || subStr === '') {
      return acc;
    }
    console.log(startIndex, endIndex, subStr);
    acc.push(text.slice(startIndex, endIndex));
    acc.push(text.slice(endIndex, endIndex + phrase.length));
    return acc;
  }, []);
}

splitByPhrase('Foo', testStr)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.