From dbadd9af83c13c8e3470fb5e3f0c5d5f85f06247 Mon Sep 17 00:00:00 2001 From: Alvaro Frias Date: Mon, 12 Apr 2021 12:38:03 -0300 Subject: [PATCH] Refactored rtrim and ltrim to use _whitespace_bytes table --- stringx.lua | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/stringx.lua b/stringx.lua index 810b222..b0568ab 100644 --- a/stringx.lua +++ b/stringx.lua @@ -216,31 +216,33 @@ function stringx.trim(s) end function stringx.ltrim(s) - if s == "" or s == string.rep(" ", s:len()) then return "" end - - local head = 1 - for i = 1, #s do - local c = s:sub(i, i) - if c ~= " " then - head = i - break - end - end - return s:sub(head) + if s == "" or s == string.rep(" ", s:len()) then + return "" + end + local head = 1 + for i = 1, #s do + if not _whitespace_bytes[s:byte(i)] then + head = i + break + end + end + return s:sub(head) end function stringx.rtrim(s) - if s == "" or s == string.rep(" ", s:len()) then return "" end - - local tail = #s - for i=#s, 1 do - local c = s:sub(i, i) - if c ~= " " then - tail = i - break - end + if s == "" or s == string.rep(" ", s:len()) then + return "" end + local tail = #s + + for i = #s, 1, -1 do + if not _whitespace_bytes[s:byte(i)] then + tail = i + break + end + end + return s:sub(1, tail) end