fix(iter): remove special case totable for map-like tables

This was originally meant as a convenience but prevents possible
functionality. For example:

  -- Get the keys of the table with even values
  local t = { a = 1, b = 2, c = 3, d = 4 }
  vim.iter(t):map(function(k, v)
    if v % 2 == 0 then return k end
  end):totable()

The example above would not work, because the map() function returns
only a single value, and cannot be converted back into a table (there
are many such examples like this).

Instead, to convert an iterator into a map-like table, users can use
fold():

  vim.iter(t):fold({}, function(t, k, v)
    t[k] = v
    return t
  end)
This commit is contained in:
Gregory Anders
2023-04-19 07:05:04 -06:00
parent 6b96122453
commit 9489406879
3 changed files with 50 additions and 51 deletions

View File

@@ -3374,13 +3374,18 @@ describe('lua stdlib', function()
end)
it('handles map-like tables', function()
local t = { a = 1, b = 2, c = 3 }
local it = vim.iter(t):map(function(k, v)
local it = vim.iter({ a = 1, b = 2, c = 3 }):map(function(k, v)
if v % 2 ~= 0 then
return k:upper(), v * 2
end
end)
eq({ A = 2, C = 6 }, it:totable())
local t = it:fold({}, function(t, k, v)
t[k] = v
return t
end)
eq({ A = 2, C = 6 }, t)
end)
it('handles table values mid-pipeline', function()
local map = {