From aa5f995ba18b016ced0eb732b195b6eb328fd66e Mon Sep 17 00:00:00 2001 From: Ray Greenwell Date: Wed, 2 Jul 2008 00:35:53 +0000 Subject: [PATCH] Added trimBeginning(), make trim() use the other two. git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@5216 542714f4-19e9-0310-aa3c-eee0fc999fb1 --- src/as/com/threerings/util/StringUtil.as | 31 +++++++++++++++--------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/as/com/threerings/util/StringUtil.as b/src/as/com/threerings/util/StringUtil.as index c98e43fe8..dfd44ab8f 100644 --- a/src/as/com/threerings/util/StringUtil.as +++ b/src/as/com/threerings/util/StringUtil.as @@ -240,20 +240,24 @@ public class StringUtil * Utility function that strips whitespace from the beginning and end of a String. */ public static function trim (str :String) :String + { + return trimEnd(trimBeginning(str)); + } + + /** + * Utility function that strips whitespace from the beginning of a String. + */ + public static function trimBeginning (str :String) :String { var startIdx :int = 0; - var endIdx :int = str.length - 1; + // this works because charAt() with an invalid index returns "", which is not whitespace while (isWhitespace(str.charAt(startIdx))) { startIdx++; } - while (endIdx > startIdx && isWhitespace(str.charAt(endIdx))) { - endIdx--; - } - if (endIdx >= startIdx) { - return str.slice(startIdx, endIdx + 1); - } else { - return ""; - } + + // TODO: is this optimization necessary? It's possible that str.slice() does the same + // check and just returns 'str' if it's the full length + return (startIdx > 0) ? str.slice(startIdx, str.length) : str; } /** @@ -261,12 +265,15 @@ public class StringUtil */ public static function trimEnd (str :String) :String { - var endIdx :int = str.length - 1; - while (isWhitespace(str.charAt(endIdx))) { + var endIdx :int = str.length; + // this works because charAt() with an invalid index returns "", which is not whitespace + while (isWhitespace(str.charAt(endIdx - 1))) { endIdx--; } - return (endIdx >= 0 ? str.slice(0, endIdx + 1) : ""); + // TODO: is this optimization necessary? It's possible that str.slice() does the same + // check and just returns 'str' if it's the full length + return (endIdx < str.length) ? str.slice(0, endIdx) : str; } /**