Skip to content

Instantly share code, notes, and snippets.

@tomatrow
Forked from RomanHargrave/assoc.fish
Last active October 28, 2017 22:32
Show Gist options
  • Save tomatrow/819ef9f8d8aa2606026d3f8e90009ebb to your computer and use it in GitHub Desktop.
Save tomatrow/819ef9f8d8aa2606026d3f8e90009ebb to your computer and use it in GitHub Desktop.
# ASCII Unit separator, purpose is to separate subrecords, etc...
set __dict_US \31
# Groks name[key] and sets varname and key variables
function dict._parsename -S -a raw
set -l data (string match -r '(.+)\[(.+)\]' $raw)
if [ (count $data) -lt 3 ]
echo "Invalid dictionary syntax '$raw'"
return 1
else
set _map_varname $data[2]
set _map_key $data[3]
return 0
end
end
# Return 0 when contains subject, print index
function dict.has_key -S -a varspec
dict._parsename $varspec; or return $status
contains -i $_map_key (string replace -ra $__dict_US.+ '' $$_map_varname) #replace all following __dict_US in each element to show only keys
end
# Remove where key matches
function dict.rm -S -a varspec
dict._parsename $varspec; or return $status
if set -l idx (dict.has_key $varspec)
set -e $_map_varname"[$idx]"
end
end
# Add/update a value
function dict.set -S -a varspec -a value
dict._parsename $varspec; or return $status
if set -l idx (dict.has_key $varspec)
if [ -z $value ]
set -e $_map_varname"[$idx]"
return 0
else
set $_map_varname"[$idx]" $_map_key$__dict_US$value
return 0
end
else
set $_map_varname $$_map_varname $_map_key$__dict_US$value
return 0
end
end
# Get a value for the given key
function dict.get -S -a varspec
dict._parsename $varspec; or return $status
if set -l idx (dict.has_key $varspec)
eval string replace -r .+$__dict_US "''" '$'$_map_varname'['$idx']'
return 0
else
return 1
end
end
function dict.serialize -S -a varname
printf '%s\n' $$varname
end
@tomatrow
Copy link
Author

I like the term dictionary better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment