elvish_config/lib/moi/util/map.elv
2021-10-13 20:49:48 +02:00

95 lines
2.0 KiB
Plaintext

fn empty [container]{ == (count $container) 0 }
fn values [container]{ keys $container | each [v]{ put $container[$v] } }
fn pvalues [container]{ keys $container | peach [v]{ put $container[$v] } }
fn value-of [container k &default=$nil]{
if (has-key $container $k) {
put $container[$k]
} else {
put $default
}
}
fn unzip [container]{
var lkeys lvalues = [] []
keys $container | each [k]{
set lkeys = [(all $lkeys) $k]
set lvalues = [(all $lvalues) $container[$k]]
}
put $lkeys $lvalues
}
fn zip [lkeys lvalues]{
var ck cv = (count $lkeys) (count $lvalues)
var c = $ck
if (> $ck $cv) {
set c = $cv
}
var result = [&]
range $c | peach [i]{
put [&k=$lkeys[$i] &i=$i]
} | peach [e]{
assoc $e v $lvalues[$e[i]]
} | each [e]{
set result[$e[k]] = $e[v]
}
put $result
}
fn to-map [@argv]{
use ./list
var container = (list:to-list $@argv)
zip [(range (count $container))] $container
}
fn to-set [@argv]{
use ./list
var m = [&]
each [k]{ set m[$k] = $nil } (list:to-list $@argv)
put $m
}
fn mdissoc [container @argv]{
each [k]{
set container = (dissoc $container $k)
} $argv
put $container
}
fn massoc [&replace=$true container @argv]{
each [e]{
var k v = $@e
if (or $replace (not (has-key $container $k))) {
set container[$k] = $v
}
} $argv
put $container
}
fn add [container key @values]{
use ./list
var values = (list:to-list $values)
if (has-key $container $key) {
set container[$key] = [(all $container[$key]) $@values]
} else {
set container[$key] = $values
}
put $container
}
fn join [container container2]{
keys $container2 | each [k]{
set container[$k] = $container2[$k]
}
put $container
}
fn sorted-keys [&reverse=$false &less-than=$nil container]{
keys $container | order &reverse=$reverse &less-than=$less-than
}
fn sorted-values [&reverse=$false &less-than=$nil container]{
values $container | order &reverse=$reverse &less-than=$less-than
}