Skip to content

Commit f917644

Browse files
committed
table: add table.slice()
1 parent 3b9c53e commit f917644

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

fusion/stdlib/table.lua

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@ function table.sort(t, ...)
3838
return t
3939
end
4040

41+
function table.slice(t, start, stop)
42+
return coroutine.wrap(function()
43+
start = start or 1
44+
stop = stop or #t
45+
for i=start, stop do
46+
coroutine.yield(t[i])
47+
end
48+
end)
49+
end
50+
4151
table.unpack = unpack or table.unpack -- luacheck: ignore 113
4252

4353
return table

spec/table_spec.lua

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,12 @@ describe("table", function()
2020
local t0 = {}
2121
assert.same(t0, table.sort(t0))
2222
end)
23+
it("can grab a slice of a table", function()
24+
local base = {'a', 'b', 'c', 'd', 'e'}
25+
local first = {'a', 'b', 'c'}
26+
local last = {'c', 'd', 'e'}
27+
assert.same(base, table.from_generator(table.slice(base)))
28+
assert.same(first, table.from_generator(table.slice(base, 1, 3)))
29+
assert.same(last, table.from_generator(table.slice(base, 3)))
30+
end)
2331
end)

0 commit comments

Comments
 (0)