DEV Community

Cover image for # Day 1 | How to resolve it?
Weijuer
Weijuer

Posted on • Updated on

# Day 1 | How to resolve it?

The Problem

var greeting = 'My name is ${name}, age ${age}, I am a ${job.jobLevel} ${job.jobName}.';
var employee = {
  name: 'XiaoMing',
  age: 11,
  job: {
    jobName: 'designer',
    jobLevel: 'senior'
  }
}

var result = greeting.render(employee);
console.log(result); // My name is XiaoMing, age 11, I am a senior designer.
Enter fullscreen mode Exit fullscreen mode

The solution

This is my solution:

// my solution
String.prototype.render = function (options) {
  return this.replace(/(?:\$\{)([\.\w]+)(?:\})/g, (match, $1) => {
    if ($1.includes('.')) {
      var p = $1.split('.');
      return p.reduce((p, n) => p[n], options);
    }
    return options[$1];
  })
}
Enter fullscreen mode Exit fullscreen mode

And the other one:

String.prototype.render = function (options) {
    with(options) {
        return eval('`' + this + '`')
    }
}
Enter fullscreen mode Exit fullscreen mode

Tips:

This is my first article, so, be kind with me.
If you see some improvement that can be made, please, let me know in the comments.
If you liked this article, please, motivate-me in the comments.

Thank you for reading ❤️ !

Top comments (0)