Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 template literal to "decompiled" array representation

Template literals, when used with tags, seem to get compiled down to an array containing the strings and the substitutions.

For example:

mytag `my name is ${'Anthony'}`

seems to get compiled down to something representing:

mytag.apply(null, [['my name is '], 'Anthony'])

My question is, how could I take `my name is ${'Anthony'}` and get the [['my name is '], 'Anthony'] "decompiled" representation?

I've included a snippet to demonstrate the above is true.

function mytag(a, ...b) {
  for (let i = 0; i < a.length; i++) {
    console.log(a[i]);
    console.log(b[i]);
  }
}

mytag`hello ${'world'}, how are ${'you'}`;

mytag.apply(null, [['hello', ', how are ', ''], 'world', 'you']);

Edit

Just to clarify my overall goal.

I'd like to have the ability to pass a template literal into a tag.

Here is a slightly more complicated example,

const myliteral = `my  name is ${() => 'Anthony'}`;
// would "decompile" to [['my name is'], f]

mytag.apply(null, fnToGetDecompiledRep(myliteral));

I'm using a function in myliteral to demonstrate that the function does not get evaluated. You can assume mytag has logic to evaluate functions.

like image 481
anthonator Avatar asked Jun 03 '26 22:06

anthonator


1 Answers

You could just make

function templateValues(...args) {
    return args;
}

and call it as

console.log(templateValues `my name is ${'Anthony'}`)
console.log(templateValues `hello ${'world'}, how are ${'you'}`;

I'd like to get the array representation without the use of a tag

const myliteral = `my  name is ${() => 'Anthony'}`;
// would "decompile" to [['my name is'], f]
mytag.apply(null, fnToGetDecompiledRep(myliteral));

No, that cannot work. myLiteral would be assigned string value that the literal expression creates here. You cannot "decompile" it afterwards. You need to use

const myParts = templateValues `my  name is ${() => 'Anthony'}`;
// same as  … = [['my name is'], () => 'Anthony'];
myTag.apply(null, myParts); // or myTag(...myParts)

There is no way around a tag to get the template values instead of a string.

like image 73
Bergi Avatar answered Jun 06 '26 13:06

Bergi