Don't try to track which variables and functions you create. Instead, run the code in a subshell. When the subshell completes, all variables and functions defined within the subshell disappear.
In bash, one way to explicitly put commands in a subshell is to place the commands inside parens: (...). For example, let's define two variables and a function within a subshell and execute the function:
$ ( a=1; b=2; fn() { echo "a=$a b=$b"; }; fn ) a=1 b=2 After the subshell completes, all are erased:
$ fn bash: fn: command not found