Sha256: 1dc90d49f94971a25c60e134ceb22b45cda317e753dea01d8a5e2aca0605e100

Contents?: true

Size: 1.45 KB

Versions: 34

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

module Katalyst
  module Content
    module HasTree
      # Constructs a tree from an ordered list of items with depth.
      #  * items that have higher depth than their predecessor are nested as `children`.
      #  * items with the same depth become siblings.
      def tree
        items.reduce(Builder.new, &:add).tree
      end

      class Builder
        attr_reader :current, :depth, :children, :tree

        def initialize
          @depth    = 0
          @children = @tree = []
        end

        def add(node)
          if node.depth == depth
            node.parent = current
            children << node
            self
          elsif node.depth > depth
            push(children.last)
            add(node)
          else
            pop
            add(node)
          end
        end

        private

        attr_writer :current, :depth, :children

        # Add node to the top of builder stacks
        def push(node)
          self.depth += 1
          self.current  = node
          self.children = node.children = []
          node
        end

        # Remove current from builder stack
        def pop
          previous = current
          self.depth -= 1
          if depth.zero?
            self.current  = nil
            self.children = tree
          else
            self.current  = previous.parent
            self.children = current.children
          end
          previous
        end
      end
    end
  end
end

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
katalyst-content-2.1.0 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-2.0.1 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-2.0.0 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-1.1.1 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-1.1.0 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-1.0.2 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-1.0.1 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-1.0.0 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-0.2.2 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-0.2.1 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-0.2.0 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-0.1.2 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-0.1.1 app/models/concerns/katalyst/content/has_tree.rb
katalyst-content-0.1.0 app/models/concerns/katalyst/content/has_tree.rb