map.lua
local tablex = require 'pl.tablex'
local utils = require 'pl.utils'
local stdmt = utils.stdmt
local tmakeset,deepcompare,merge,keys,difference,tupdate = tablex.makeset,tablex.deepcompare,tablex.merge,tablex.keys,tablex.difference,tablex.update
local pretty_write = require 'pl.pretty' . write
local Map = stdmt.Map
local Set = stdmt.Set
local List = stdmt.List
local class = require 'pl.class'
class(nil,nil,Map)
local function makemap (m)
return setmetatable(m,Map)
end
function Map:_init (t)
local mt = getmetatable(t)
if mt == Set or mt == Map then
self:update(t)
else
return t end
end
local function makelist(t)
return setmetatable(t,List)
end
Map.keys = tablex.keys
Map.values = tablex.values
function Map:iter ()
return pairs(self)
end
function Map:items()
local ls = makelist(tablex.pairmap (function (k,v) return makelist {k,v} end, self))
ls:sort(function(t1,t2) return t1[1] < t2[1] end)
return ls
end
function Map:setdefault(key, defaultval)
return self[key] or self:set(key,defaultval) or defaultval
end
Map.len = tablex.size
function Map:set (key,val)
self[key] = val
end
function Map:get (key)
return rawget(self,key)
end
local index_by = tablex.index_by
function Map:getvalues (keys)
return makelist(index_by(self,keys))
end
Map.update = tablex.update
function Map:__eq (m)
return deepcompare(self,m,true)
end
function Map:__tostring ()
return pretty_write(self,'')
end
return Map