Skip to content

Commit

Permalink
optimization: use ternary if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
jfschwarz committed Feb 11, 2022
1 parent 0fcaad5 commit cb6b396
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
20 changes: 19 additions & 1 deletion src/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,28 @@ ${options.contract ? "contract" : "library"} ${options.name || "Template"} {
narrowInput(scope.inputType, conditionResolvedPath, "bool")

const negate = statement.path.head === "unless"
const condition = `${negate ? "!" : ""}${conditionResolvedPath}`

const containsSingleAppend =
statement.program.body.length === 1 &&
statement.program.body[0].type !== "BlockStatement"

// Optimization: use ternary if possible
if (containsSingleAppend) {
const [singleAppend] = processStatement(statement.program.body[0], scope)
if (
singleAppend &&
"append" in singleAppend &&
singleAppend.append.length === 1
) {
const [appendStr] = singleAppend.append
return [{ append: [`${condition} ? ${appendStr} : ""`] }]
}
}

return [
{
line: `if(${negate ? "!" : ""}${conditionResolvedPath}) {`,
line: `if(${condition}) {`,
},
...processProgram(statement.program, scope),
{
Expand Down
14 changes: 5 additions & 9 deletions test/cases/wand.only/Template.sol
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,13 @@ contract Template {
__result,
' <g\n style="transform: rotate(calc(',
uint2str(__i),
' * 15deg)) translateY(-520px);"\n >\n '
' * 15deg)) translateY(-520px);"\n >\n ',
__input.rhythm[__i].halo0 ? '<use href="#h0"></use>' : "",
"\n ",
__input.rhythm[__i].halo1 ? '<use href="#h1"></use>' : "",
"\n </g>\n"
)
);
if (__input.rhythm[__i].halo0) {
__result = string(abi.encodePacked(__result, '<use href="#h0"></use>'));
}
__result = string(abi.encodePacked(__result, "\n "));
if (__input.rhythm[__i].halo1) {
__result = string(abi.encodePacked(__result, '<use href="#h1"></use>'));
}
__result = string(abi.encodePacked(__result, "\n </g>\n"));
}
__result = string(abi.encodePacked(__result, "</g>"));
}
Expand Down

0 comments on commit cb6b396

Please sign in to comment.