Sha256: b6f6f6e75cb2ae67b2b15a06a793e500f86c895d698be959113085d34c5f8bde

Contents?: true

Size: 1.64 KB

Versions: 2

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

module TTY
  class Prompt
    # @api private
    class SelectedChoices
      include Enumerable

      attr_reader :size

      # Create selected choices
      #
      # @param [Array<Choice>] selected
      # @param [Array<Integer>] indexes
      #
      # @api public
      def initialize(selected = [], indexes = [])
        @selected = selected
        @indexes = indexes
        @size = @selected.size
      end

      # Clear selected choices
      #
      # @api public
      def clear
        @indexes.clear
        @selected.clear
        @size = 0
      end

      # Iterate over selected choices
      #
      # @api public
      def each(&block)
        return to_enum unless block_given?

        @selected.each(&block)
      end

      # Insert choice at index
      #
      # @param [Integer] index
      # @param [Choice] choice
      #
      # @api public
      def insert(index, choice)
        insert_idx = find_index_by { |i| index < @indexes[i] }
        insert_idx ||= -1
        @indexes.insert(insert_idx, index)
        @selected.insert(insert_idx, choice)
        @size += 1
        self
      end

      # Delete choice at index
      #
      # @return [Choice]
      #   the deleted choice
      #
      # @api public
      def delete_at(index)
        delete_idx = @indexes.each_index.find { |i| index == @indexes[i] }
        return nil unless delete_idx

        @indexes.delete_at(delete_idx)
        choice = @selected.delete_at(delete_idx)
        @size -= 1
        choice
      end

      def find_index_by(&search)
        (0...@size).bsearch(&search)
      end
    end # SelectedChoices
  end # Prompt
end # TTY

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
tty-prompt-0.23.1 lib/tty/prompt/selected_choices.rb
tty-prompt-0.23.0 lib/tty/prompt/selected_choices.rb