Skip to content

Implement string literal trim() folding #2900

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ private Node tryFoldKnownStringMethods(Node subtree, Node callTarget) {
return tryFoldStringToLowerCase(subtree, stringNode);
case "toUpperCase":
return tryFoldStringToUpperCase(subtree, stringNode);
case "trim":
return tryFoldStringTrim(subtree, stringNode);
default: // fall out
}
} else {
Expand Down Expand Up @@ -319,6 +321,20 @@ private Node tryFoldStringToUpperCase(Node subtree, Node stringNode) {
return replacement;
}

/**
* @return The trimmed string Node.
*/
private Node tryFoldStringTrim(Node subtree, Node stringNode) {
// See ECMA 15.5.4.20, 7.2, and 7.3
// All Unicode 10.0 whitespace + BOM
String whitespace = "[ \t\n-\r\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+";
String trimmed = stringNode.getString().replaceAll("^" + whitespace + "|" + whitespace + "$", "");
Node replacement = IR.string(trimmed);
subtree.replaceWith(replacement);
compiler.reportChangeToEnclosingScope(replacement);
return replacement;
}

/**
* @param input string representation of a number
* @return string with leading and trailing zeros removed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ public void testTemplateStringsKnownMethods() {
test("x = `abcdef`.charCodeAt(0)", "x = 97");
test("x = `abc`.toUpperCase()", "x = 'ABC'");
test("x = `ABC`.toLowerCase()", "x = 'abc'");
test("x = `\t\n\uFEFF\t asd foo bar \r\n`.trim()", "x = 'asd foo bar'");
test("x = parseInt(`123`)", "x = 123");
test("x = parseFloat(`1.23`)", "x = 1.23");
}
Expand Down