Browse files

refactorized string:squeeze

  • Loading branch information...
1 parent 18df642 commit 28ba724946c8cecda78562154e8923a5945d757e @kikito committed Apr 30, 2011
Showing with 9 additions and 25 deletions.
  1. +9 −25 strong.lua
View
34 strong.lua
@@ -191,33 +191,17 @@ function string:squeeze(other)
if other then
return self:gsub(other .. other .. '+', other)
else
- local last -- The last character seen
- local count = 1 -- Used to track how many identical characters in a row have been seen
-
- -- Because we're gsubing, we're changing the length of the string mid-loop.
- -- The loop keeps using the original length. These variables help us to adjust
- -- the iterator variable to what it should be.
- local diff = 0 -- difference between current length and original length
- local origLen = #self
-
- for i = 1, origLen do
- i = i - diff
- local c = self[i]
-
- if c == last then
- count = count + 1
- elseif count > 1 then
- self = self:sub(1, i - count) .. self:sub(i)
- diff = origLen - #self
- count = 1
+ local last, current
+ local buffer = {}
+
+ for i = 1, #self do
+ current = self[i]
+ if current ~= last then
+ table.insert(buffer, current)
+ last = current
end
-
- last = c
end
-
- -- if the last character was a repition we must take care of it here, as loop has ended
- if count > 1 then self = self:sub(1, #self - count) .. self[#self] end
- return self
+ return table.concat(buffer)
end
end

0 comments on commit 28ba724

Please sign in to comment.