Re: store bug
- Posted by jmduro Mar 09, 2021
- 964 views
This should be a good replacement for store and fetch:
include std/text.e include std/search.e include std/error.e -------------------------------------------------------------------------------- function get_nested(object structure, sequence targetPath, object def=0, sequence currentPath={}) if equal(currentPath, targetPath) then return structure else integer digit = targetPath[length(currentPath)+1] if digit <= length(structure) then return get_nested(structure[digit], targetPath, def, currentPath&digit) else return def end if end if end function -------------------------------------------------------------------------------- function set_nested(object structure, sequence targetPath, object x, sequence currentPath={}) integer digit = targetPath[length(currentPath)+1] for i = 1 to digit do if i > length(structure) then structure = append(structure, {}) end if if i = digit then if equal(currentPath&{i}, targetPath) then structure[i] = x else structure[i] = set_nested(structure[i], targetPath, x, currentPath&i) end if end if end for return structure end function -------------------------------------------------------------------------------- public function store(object structure, sequence targetPath, object x) if length(targetPath) = 0 then crash_message("Target path cannot be empty!\n") end if return set_nested(structure, targetPath, x) end function -------------------------------------------------------------------------------- public function fetch(object structure, sequence targetPath, object def=0) if length(targetPath) = 0 then crash_message("Target path cannot be empty!\n") end if return get_nested(structure, targetPath, def) end function -------------------------------------------------------------------------------- public function remove_nested(object structure, sequence targetPath, sequence currentPath={}) integer digit = targetPath[length(currentPath)+1] if digit <= length(structure) then if equal(currentPath&{digit}, targetPath) then structure = remove(structure, digit) else structure[digit] = remove_nested(structure[digit], targetPath, currentPath&digit) end if end if return structure end function