Skip to content

Commit

Permalink
Implement string literal trim() folding
Browse files Browse the repository at this point in the history
Closes #2900

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=194607689
  • Loading branch information
puddly authored and lauraharker committed Apr 30, 2018
1 parent ac3f219 commit 40fe067
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
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

0 comments on commit 40fe067

Please sign in to comment.