Last active
August 26, 2020 21:33
-
-
Save Allen-B1/1ac8e9af9efa072c724710814552bd06 to your computer and use it in GitHub Desktop.
Fish: dictionaries / associative arrays / maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dict | |
set arg_dict (echo $argv[2] | string replace -ar "[^A-Za-z0-9]+" "_") | |
set arg_key (echo $argv[3] | string replace -ar "[^A-Za-z0-9]+" "_") | |
switch $argv[1] | |
case "set" | |
if test (count $argv) -gt 3 | |
set -g $arg_dict'_'$arg_key $argv[4..-1] | |
else | |
set -g $arg_dict'_'$arg_key | |
end | |
case "remove" | |
for rawkey in $argv[3..-1] | |
set arg_key (echo $rawkey | string replace -ar "[^A-Za-z0-9]+" "_") | |
set -e $arg_dict'_'$arg_key | |
end | |
case "clear" | |
for pair in (set) | |
set varname (echo $pair | string split " ")[1] | |
if test (echo $varname | string sub -l (math (echo $arg_dict | string length) + 1)) = $arg_dict'_' | |
set -e $varname | |
end | |
end | |
case "keys" | |
for pair in (set) | |
set varname (echo $pair | string split " ")[1] | |
if test (echo $varname | string sub -l (math (echo $arg_dict | string length) + 1)) = $arg_dict'_' | |
set keyname (echo $varname | string sub -s (math (echo $arg_dict | string length) + 2)) | |
echo $keyname | |
end | |
end | |
case "get" | |
if test (eval count '$'$arg_dict'_'$arg_key) -ne 0 | |
eval printf "'%s\n'" '$'$arg_dict'_'$arg_key | |
end | |
case "has" | |
set -q $arg_dict'_'$arg_key | |
case "*" | |
echo "Invalid command: $argv[1]" 2>&1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment