diff options
author | Norbert Preining <norbert@preining.info> | 2021-09-20 03:02:23 +0000 |
---|---|---|
committer | Norbert Preining <norbert@preining.info> | 2021-09-20 03:02:23 +0000 |
commit | c9fcf97bc045a9d020980c33b6c7c1ee5aedef99 (patch) | |
tree | bf74a43623e081cad4b72a752730aeff86b7c5cf /macros/luatex/generic/penlight/pl/MultiMap.lua | |
parent | 996c9b239bde82dc3ef3e5b69cd525e87fdb61a8 (diff) |
CTAN sync 202109200302
Diffstat (limited to 'macros/luatex/generic/penlight/pl/MultiMap.lua')
-rw-r--r-- | macros/luatex/generic/penlight/pl/MultiMap.lua | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/macros/luatex/generic/penlight/pl/MultiMap.lua b/macros/luatex/generic/penlight/pl/MultiMap.lua new file mode 100644 index 0000000000..0abe84de02 --- /dev/null +++ b/macros/luatex/generic/penlight/pl/MultiMap.lua @@ -0,0 +1,54 @@ +--- MultiMap, a Map which has multiple values per key. +-- +-- Dependencies: `pl.utils`, `pl.class`, `pl.List`, `pl.Map` +-- @classmod pl.MultiMap + +local utils = require 'pl.utils' +local class = require 'pl.class' +local List = require 'pl.List' +local Map = require 'pl.Map' + +-- MultiMap is a standard MT +local MultiMap = utils.stdmt.MultiMap + +class(Map,nil,MultiMap) +MultiMap._name = 'MultiMap' + +function MultiMap:_init (t) + if not t then return end + self:update(t) +end + +--- update a MultiMap using a table. +-- @param t either a Multimap or a map-like table. +-- @return the map +function MultiMap:update (t) + utils.assert_arg(1,t,'table') + if Map:class_of(t) then + for k,v in pairs(t) do + self[k] = List() + self[k]:append(v) + end + else + for k,v in pairs(t) do + self[k] = List(v) + end + end +end + +--- add a new value to a key. Setting a nil value removes the key. +-- @param key the key +-- @param val the value +-- @return the map +function MultiMap:set (key,val) + if val == nil then + self[key] = nil + else + if not self[key] then + self[key] = List() + end + self[key]:append(val) + end +end + +return MultiMap |