batteries/sequence.lua

86 lines
1.8 KiB
Lua
Raw Normal View History

--[[
sequence - functional + oo wrapper for ordered tables
mainly beneficial when used for method chaining
to save on typing and data plumbing
]]
local path = (...):gsub("sequence", "")
local class = require(path .. "class")
local table = require(path .. "tablex") --shadow global table module
local functional = require(path .. "functional")
2020-06-02 05:01:21 +00:00
local stable_sort = require(path .. "sort").stable_sort
local sequence = class(table) --proxy missing table fns to tablex api
2020-03-15 10:22:22 +00:00
--upgrade a table into a sequence, or create a new sequence
function sequence:new(t)
return self:init(t or {})
end
2020-06-02 05:01:21 +00:00
--sorting default to stable
sequence.sort = stable_sort
--patch various interfaces in a type-preserving way, for method chaining
--import copying tablex
function sequence:keys()
2020-06-02 05:01:21 +00:00
return sequence(table.keys(self))
end
function sequence:values()
2020-06-02 05:01:21 +00:00
return sequence(table.values(self))
end
2020-06-02 05:01:21 +00:00
function sequence:dedupe()
return sequence(table.dedupe(self))
end
2020-06-02 05:01:21 +00:00
function sequence:append(...)
return sequence(table.append(self, ...))
end
function sequence:overlay(...)
return sequence(table.overlay(self, ...))
end
function sequence:copy(...)
return sequence(table.copy(self, ...))
end
--import functional interface
function sequence:foreach(f)
return functional.foreach(self, f)
end
function sequence:reduce(f, o)
2020-04-07 06:19:38 +00:00
return functional.reduce(self, f, o)
end
function sequence:map(f)
return sequence(functional.map(self, f))
end
function sequence:remap(f)
return functional.remap(self, f)
end
function sequence:filter(f)
return sequence(functional.filter(self, f))
end
function sequence:remove_if(f)
return sequence(functional.remove_if(self, f))
end
function sequence:partition(f)
local a, b = functional.partition(self, f)
return sequence(a), sequence(b)
end
function sequence:zip(other, f)
return sequence(functional.zip(self, other, f))
end
2020-06-02 05:01:21 +00:00
return sequence