We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Iterator:fold
Iterator:enumerate
1 parent 102c029 commit a5ca150Copy full SHA for a5ca150
2 files changed
lua/plenary/iterators.lua
@@ -486,6 +486,16 @@ function Iterator:filter(fun)
486
return wrap(filter_gen, { self.gen, self.param, fun }, self.state)
487
end
488
489
+---Iterator adapter that will provide numbers from 1 to n as the first multival
490
+---@return Iterator
491
+function Iterator:enumerate()
492
+ local i = 0
493
+ return self:map(function(...)
494
+ i = i + 1
495
+ return i, ...
496
+ end)
497
+end
498
+
499
--------------------------------------------------------------------------------
500
-- Reducing
501
@@ -531,6 +541,19 @@ function Iterator:find(val_or_fn)
531
541
532
542
533
543
544
+---Folds an iterator into a single value using a function.
545
+---@param init any
546
+---@param fun fun(acc: any, val: any): any
547
+---@return any
548
+function Iterator:fold(init, fun)
549
+ local acc = init
550
+ local gen, param, state = self.gen, self.param, self.state
551
+ for _, r in gen, param, state do
552
+ acc = fun(acc, r)
553
+ end
554
+ return acc
555
556
534
557
---Turns an iterator into a list.
535
558
---If the iterator yields multivals only the first multival will be used.
536
559
---@return table
tests/plenary/iterators_spec.lua
@@ -31,6 +31,35 @@ describe("iterators", function()
31
check_keys(tbl, { 1, 2, 3, 4 })
32
end)
33
34
+ it("should be able to fold", function()
35
+ local numbers = { 1, 2, 3, 4 }
36
+ local result = i.iter(numbers):fold(0, function(a, v)
37
+ return a + v
38
39
+ eq(result, 10)
40
41
+ local strings = { "hello", "world", "this", "is", "a", "test" }
42
+ result = i.iter(strings):fold("", function(a, v)
43
+ return a .. v
44
45
+ eq(result, "helloworldthisisatest")
46
47
48
+ it("should be able to enumerate", function()
49
+ local tbl = { 1, 2, 3, 4 }
50
+ local results = i.iter(tbl)
51
+ :enumerate()
52
+ :map(function(idx, v)
53
+ return { idx, v }
54
55
+ :tolist()
56
+ eq(#results, 4)
57
+ eq(results[1], { 1, 1 })
58
+ eq(results[2], { 2, 2 })
59
+ eq(results[3], { 3, 3 })
60
+ eq(results[4], { 4, 4 })
61
62
63
it("should be able to find", function()
64
local tbl = { 1, 2, 3, 4 }
65
local tbl_iter = i.iter(tbl)
0 commit comments