Mark
Mark

Reputation: 43

Faster way to eval multiple strings javascript

The code below evaluates any code within "{{" and "}}", I managed to do it, but it is very slow, how to achieve the same result but in a faster way?

I'm not very familiar with regex replacement or something similar, so I'm struggling to get a better result.

console.time("Time");

String.prototype.eval = function(){
  if(this.includes("{{") && this.includes("}}")){
    const result = [];
    const str = this.split("{{");
    
    for(let i = 0; i < str.length; i++){
      if(i === 0){
        result.push(str[i]);
        continue;
      }
      result.push(Function(`return ${str[i].split("}}")[0]}`)());
      result.push(str[i].split("}}")[1]);    
    }
    
    return result.join("");
  }
  return this;
}

const person = { name:"John Doe", age:55 };
const func = () => "cool!!";

console.log(`Hi {{person.name}}, you are {{person.age}} years old, {{func()}}`.eval());

console.timeEnd("Time");

Upvotes: 1

Views: 272

Answers (1)

Ravikumar
Ravikumar

Reputation: 2205

You can do like this with RegEx, but I don't see it saved some time.

console.time("Time");

String.prototype.eval = function() {
    return this.replace(/{{(.*?)}}/g, (match, key) => Function(`return ${key}`)());
}

const person = {
    name: "John Doe",
    age: 55
};
const func = ()=>"cool!!";

console.log(`Hi {{person.name}}, you are {{person.age}} years old, {{func()}}`.eval());

console.timeEnd("Time");

Upvotes: 1

Related Questions