Pretty Tree Generator

Published by Theldoria in

Write the pretty tree generator function pretty_tree_list.

  • The function should accept a tree as its first argument. A tree in this case is:
    • a hash whose keys are the element names, given as strings
    • and whose values are sub-trees.
  • A second boolean optional argument should be accepted. The behaviour should be:
    • If not given or set to false: use the hash keys in the order of the hash.
    • If set to true: sort the hash keys.
  • The function should return a list of strings, one for each tree element, with the following properties:
    • The first element should be the root key of the tree.
    • Each sub-tree element should be in its own ident level.
    • Each indent level should be three characters wide.
    • The characters used to indent should be composed of |, +, - and , such that the tree / sub-tree element relation is visible (see examples below).
      • A sub-tree element shall be introduced with +--.
      • Extend the sub-tree indentation with | in case of sub-sub-tree elements.
      • Do not extend sub-tree with | for the last element.
  • The returned list is intended to be printed to standard output in given order.

Examples

The following examples show what one should see if the returned list for the given input is printed:

pretty_tree_list('foo'=>{'boo' => {}, 'bar' => {'baz' => nil}}).each {|e| puts e}
➞
foo
+--boo
+--bar
   +--baz

pretty_tree_list('foo'=>{'bar' => {'baz' => {}}, 'boo' => nil}).each {|e| puts e}
➞
foo
+--bar
|  +--baz
+--boo

pretty_tree_list({'foo'=>{'boo' => {}, 'bar' => {'baz' => {}}}}, true).each {|e| puts e}
➞
foo
+--bar
|  +--baz
+--boo

Notes

N/A

Watch a quick demo on how Edabit works.