Software /
code /
prosody
Comparison
util/iterators.lua @ 8797:7b621a4a2e8d
util.iterators: Add join() method and tests
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Fri, 18 May 2018 14:57:39 +0100 |
parent | 8389:5d866eb8f18f |
child | 9327:f6f1dec164b5 |
comparison
equal
deleted
inserted
replaced
8796:51375b007239 | 8797:7b621a4a2e8d |
---|---|
12 | 12 |
13 local t_insert = table.insert; | 13 local t_insert = table.insert; |
14 local select, next = select, next; | 14 local select, next = select, next; |
15 local unpack = table.unpack or unpack; --luacheck: ignore 113 143 | 15 local unpack = table.unpack or unpack; --luacheck: ignore 113 143 |
16 local pack = table.pack or function (...) return { n = select("#", ...), ... }; end -- luacheck: ignore 143 | 16 local pack = table.pack or function (...) return { n = select("#", ...), ... }; end -- luacheck: ignore 143 |
17 local type = type; | |
18 local table, setmetatable = table, setmetatable; | |
19 | |
20 local _ENV = nil; | |
21 --luacheck: std none | |
17 | 22 |
18 -- Reverse an iterator | 23 -- Reverse an iterator |
19 function it.reverse(f, s, var) | 24 function it.reverse(f, s, var) |
20 local results = {}; | 25 local results = {}; |
21 | 26 |
182 t[var] = var2; | 187 t[var] = var2; |
183 end | 188 end |
184 return t; | 189 return t; |
185 end | 190 end |
186 | 191 |
192 local function _join_iter(j_s, j_var) | |
193 local iterators, current_idx = j_s[1], j_s[2]; | |
194 local f, s, var = unpack(iterators[current_idx], 1, 3); | |
195 if j_var ~= nil then | |
196 var = j_var; | |
197 end | |
198 local ret = pack(f(s, var)); | |
199 local var1 = ret[1]; | |
200 if var1 == nil then | |
201 -- End of this iterator, advance to next | |
202 if current_idx == #iterators then | |
203 -- No more iterators, return nil | |
204 return; | |
205 end | |
206 j_s[2] = current_idx + 1; | |
207 return _join_iter(j_s); | |
208 end | |
209 return unpack(ret, 1, ret.n); | |
210 end | |
211 local join_methods = {}; | |
212 local join_mt = { | |
213 __index = join_methods; | |
214 __call = function (t, s, var) --luacheck: ignore 212/t | |
215 return _join_iter(s, var); | |
216 end; | |
217 }; | |
218 | |
219 function join_methods:append(f, s, var) | |
220 table.insert(self, { f, s, var }); | |
221 return self, { self, 1 }; | |
222 end | |
223 | |
224 function join_methods:prepend(f, s, var) | |
225 table.insert(self, { f, s, var }, 1); | |
226 return self, { self, 1 }; | |
227 end | |
228 | |
229 function it.join(f, s, var) | |
230 return setmetatable({ {f, s, var} }, join_mt); | |
231 end | |
232 | |
187 return it; | 233 return it; |