From 5b40a1c09dda83275784053b325ad16626fc55f2 Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Tue, 5 Dec 2023 18:35:22 -0800 Subject: [PATCH] feat(lua): implement Iter:join() (#26416) --- runtime/doc/lua.txt | 13 +++++++++++++ runtime/lua/vim/iter.lua | 12 ++++++++++++ test/functional/lua/iter_spec.lua | 5 +++++ 3 files changed, 30 insertions(+) diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index a35d70cae8..f7f722bc0e 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -3410,6 +3410,19 @@ Iter:fold({init}, {f}) *Iter:fold()* Return: ~ any +Iter:join({delim}) *Iter:join()* + Collect the iterator into a delimited string. + + Each element in the iterator is joined into a string separated by {delim}. + + Consumes the iterator. + + Parameters: ~ + • {delim} (string) Delimiter + + Return: ~ + (string) + Iter:last() *Iter:last()* Drains the iterator and returns the last item. diff --git a/runtime/lua/vim/iter.lua b/runtime/lua/vim/iter.lua index 874bdfb437..e9c2b66bf2 100644 --- a/runtime/lua/vim/iter.lua +++ b/runtime/lua/vim/iter.lua @@ -356,6 +356,18 @@ function ListIter.totable(self) return self._table end +--- Collect the iterator into a delimited string. +--- +--- Each element in the iterator is joined into a string separated by {delim}. +--- +--- Consumes the iterator. +--- +--- @param delim string Delimiter +--- @return string +function Iter.join(self, delim) + return table.concat(self:totable(), delim) +end + --- Folds ("reduces") an iterator into a single value. --- --- Examples: diff --git a/test/functional/lua/iter_spec.lua b/test/functional/lua/iter_spec.lua index ffa28e7b11..2d28395c59 100644 --- a/test/functional/lua/iter_spec.lua +++ b/test/functional/lua/iter_spec.lua @@ -91,6 +91,11 @@ describe('vim.iter', function() end end) + it('join()', function() + eq('1, 2, 3', vim.iter({1, 2, 3}):join(', ')) + eq('a|b|c|d', vim.iter(vim.gsplit('a|b|c|d', '|')):join('|')) + end) + it('next()', function() local it = vim.iter({1, 2, 3}):map(function(v) return 2 * v end) eq(2, it:next())