0

I'm trying to implement my own template literals functionality (in educational purposes), but I can't understand how it works.

My idea is to extend String.prototype with function, that will eval every ${} sequence inside the string. The problem is my new function don't know context (variables inside the string). Here's how I think it should work:

String.prototype.smart_eval = function() { /* find all ${} and eval them */ }

function some_function() {
  let a = 1;
  let b = 2;
  return 'A is ${a}, B is ${b}, the sum is ${a + b}'.smart_eval()
}

This will cause Uncaught ReferenceError: a is not defined since a and b belong to some_function(), not smart_eval(). Is there any elegant way to solve this without using function arguments or .call() / .apply()?

1 Answer 1

0

So... It seems I want something, that is not possible. My first idea to solve this as smooth as possible is Python-like function format. I don't qualify this piece of code as 100% working solution, but maybe somebody will find it usable.

String.prototype.format=function(values) {
  let s = this;
  let r = '';
  for (let i = 0; i < s.length; i++) {
    if (s[i] == '{') {
      for (let t = i+1; t < s.length; t++) {
        if (s[t] == '}') {
          let d = s.substring(i + 1, t);
          try { d = parseInt(d) }
          catch(err) { d = false } 
          finally {
            if (d !== false) {
              if (values.length >= d + 1) { r += values[d]; i = t; break; }
              else { throw new ReferenceError('Literal is out of values range.') }
            }
          }
        }
      }
    } else {
      r += s[i] || ''
    }
  }
  return r
}

Examples:

'Hello {0}!'.format(['there']) // output: 'Hello there!'
'G{0}n{0}ral K{0}n{1}.'.format(['e', 'obi']) // output: 'General Kenobi.'

If you don't need IE11 support and some other browsers you can use rest parameters in function definition:

String.prototype.format=function(...values) {

And call it in more convenient way (without wrapping parameters into array):

'{1} wanna {0}? Let\'s {0}!'.format('play', 'You') // output: 'You wanna play? Let's play!'
Sign up to request clarification or add additional context in comments.

1 Comment

code is pretty complicated... simple reg exp is how most people would have solved it. stackoverflow.com/questions/36994853/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.