Skip to content

Commit 40fe067

Browse files
puddlylauraharker
authored andcommitted
Implement string literal trim() folding
Closes #2900 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=194607689
1 parent ac3f219 commit 40fe067

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java

+16
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,8 @@ private Node tryFoldKnownStringMethods(Node subtree, Node callTarget) {
218218
return tryFoldStringToLowerCase(subtree, stringNode);
219219
case "toUpperCase":
220220
return tryFoldStringToUpperCase(subtree, stringNode);
221+
case "trim":
222+
return tryFoldStringTrim(subtree, stringNode);
221223
default: // fall out
222224
}
223225
} else {
@@ -319,6 +321,20 @@ private Node tryFoldStringToUpperCase(Node subtree, Node stringNode) {
319321
return replacement;
320322
}
321323

324+
/** @return The trimmed string Node. */
325+
private Node tryFoldStringTrim(Node subtree, Node stringNode) {
326+
// See ECMA 15.5.4.20, 7.2, and 7.3
327+
// All Unicode 10.0 whitespace + BOM
328+
String whitespace =
329+
"[ \t\n-\r\\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF]+";
330+
String trimmed =
331+
stringNode.getString().replaceAll("^" + whitespace + "|" + whitespace + "$", "");
332+
Node replacement = IR.string(trimmed);
333+
subtree.replaceWith(replacement);
334+
compiler.reportChangeToEnclosingScope(replacement);
335+
return replacement;
336+
}
337+
322338
/**
323339
* @param input string representation of a number
324340
* @return string with leading and trailing zeros removed

test/com/google/javascript/jscomp/PeepholeIntegrationTest.java

+1
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,7 @@ public void testTemplateStringsKnownMethods() {
377377
test("x = `abcdef`.charCodeAt(0)", "x = 97");
378378
test("x = `abc`.toUpperCase()", "x = 'ABC'");
379379
test("x = `ABC`.toLowerCase()", "x = 'abc'");
380+
test("x = `\t\n\uFEFF\t asd foo bar \r\n`.trim()", "x = 'asd foo bar'");
380381
test("x = parseInt(`123`)", "x = 123");
381382
test("x = parseFloat(`1.23`)", "x = 1.23");
382383
}

0 commit comments

Comments
 (0)