Skip to content

Instantly share code, notes, and snippets.

@madis
Last active October 16, 2016 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madis/fb0febeb75c6a2b788e028aa88942d01 to your computer and use it in GitHub Desktop.
Save madis/fb0febeb75c6a2b788e028aa88942d01 to your computer and use it in GitHub Desktop.
def build_tree(root_id:)
root_row = db_find(id: root_id)
root_node =
{
id: root_id,
text: root_row[:text]
}
add_children(root_node, db_find_children(parent_id: root_id))
root_node
end
def add_children(node, child_rows)
node[:children] = child_rows.map do |cr|
{
id: cr[:id],
text: cr[:text],
children: add_children(cr, db_find_children(parent_id: cr[:id]))
}
end
end
DATABASE = [
{id: 1, parent_id: nil, text: 'i am root'},
{id: 2, parent_id: 1, text: '1st child of 1'},
{id: 3, parent_id: 1, text: '2nd child of 1'},
{id: 4, parent_id: 2, text: '1st child of 2'}
]
def db_find(id:)
DATABASE.find { |row| row[:id] == id}
end
def db_find_children(parent_id:)
DATABASE.find_all { |row| row[:parent_id] == parent_id }.map(&method(:format_node))
end
def format_node(db_row)
{
id: db_row[:id],
text: db_row[:text],
}
end
describe 'build_tree' do
context 'depth 1' do
subject { build_tree(root_id: 4) }
it { should eq id: 4, text: '1st child of 2', children: [] }
end
context 'depth 2' do
subject { build_tree(root_id: 2) }
let :expected_tree do
{
id: 2,
text: '1st child of 1',
children: [
{
id: 4,
text: '1st child of 2',
children: []
}
]
}
end
it { should eq expected_tree }
end
context 'depth 3' do
subject { build_tree(root_id: 1) }
let(:expected_tree) do
{
id: 1,
text: 'i am root',
children: [
{
id: 2,
text: '1st child of 1',
children: [
{id: 4, text: '1st child of 2', children: []}
]
},
{id: 3, text: '2nd child of 1', children: []}
]
}
end
it { should eq expected_tree }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment