Skip to content

Commit

Permalink
Share same template quasi array with all identical calls
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed Dec 5, 2017
1 parent 2db8c74 commit 6272cc0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/program/Program.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export default function Program(source, ast, transforms, options) {
wrap((this.body = ast), this);
this.body.__proto__ = BlockStatement.prototype;

this.templateLiteralQuasis = Object.create(null);

this.indentExclusionElements = [];
this.body.initialise(transforms);

Expand Down
14 changes: 10 additions & 4 deletions src/program/types/TaggedTemplateExpression.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,21 @@ export default class TaggedTemplateExpression extends Node {
.concat(this.quasi.quasis)
.sort((a, b) => a.start - b.start);

const root = this.findNearest('Program');
const program = this.program;
const rootScope = program.body.scope;

// insert strings at start
const templateStrings = this.quasi.quasis.map(quasi =>
JSON.stringify(quasi.value.cooked)
);
).join(', ');

let templateObject = this.program.templateLiteralQuasis[templateStrings];
if (!templateObject) {
templateObject = rootScope.createIdentifier('templateObject');
code.prependRight(0, `var ${templateObject} = Object.freeze([${templateStrings}]);\n`);

const templateObject = root.scope.createIdentifier('templateObject');
code.prependRight(0, `var ${templateObject} = Object.freeze([${templateStrings.join(', ')}]);\n`);
this.program.templateLiteralQuasis[templateStrings] = templateObject;
}

code.overwrite(
this.tag.end,
Expand Down
7 changes: 7 additions & 0 deletions test/samples/template-strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ module.exports = [
output: `var templateObject = Object.freeze(["", "y"]);\nvar str = x(templateObject, (function () { return 42; })());`
},

{
description: 'reuses quasi array for identical tagged template strings',
options: { transforms: { dangerousTaggedTemplateString: true } },
input: 'x`a${a}b`, x`a${b}b`, x`b${c}a`',
output: `var templateObject$1 = Object.freeze(["b", "a"]);\nvar templateObject = Object.freeze(["a", "b"]);\nx(templateObject, a), x(templateObject, b), x(templateObject$1, c)`
},

{
description: 'parenthesises template strings as necessary',
input: 'var str = `x${y}`.toUpperCase();',
Expand Down

0 comments on commit 6272cc0

Please sign in to comment.