interpolation

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
replace
const interpolateString = (input, dictionary) => {
  if(typeof input !== 'string' || !dictionary || dictionary !== Object(dictionary)){
    return input;
  }

  return input.replace(/\{(\w+)}/g, (match, word) => (
    dictionary?.[word] ? dictionary[word] : word
  ));
}
const greeting = interpolateString('Hello, {boo} my name is {name} and I am {age} years old. Cheers {name}', { name: 'John', age: 30 });
ready
iterate
const interpolateString = (input, dictionary) => {
  let output = '';

  if(typeof input !== 'string' || !dictionary || dictionary !== Object(dictionary) && input.length>2){
    return input;
  }

  let left = 0;
  let right = 1;
  let matcher = '';

  while(left < input.length){
    if(input[left] !== "{"){
      output += input[left];
      left += 1;
      right = left + 1;
    }else{
      if(input[right] === "}"){
        output += dictionary?.[matcher] ? dictionary[matcher] : `{${matcher}}`;
        matcher = '';
        left = right + 1;
        right = left + 1;
      }else{
        matcher += input[right];
        right += 1;
      }
    }
  }

  return output
}
const greeting = interpolateString('Hello, {boo} my name is {name} and I am {age} years old. Cheers {name}', { name: 'John', age: 30 });
ready

Revisions

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