Sha256: 1ad1b3a5649b5e86935c9c88f6a728e7677457d70d6cbad7180569381d03c918

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

module Melisa
  class Search
    include Enumerable
    
    def initialize(trie, prefix)
      @trie = trie
      @prefix = prefix
    end

    def search(prefix)
      Search.new(@trie, @prefix + prefix)
    end

    def reset_agent
      # Reset the agent state so predictive_search iterates through all keys
      @agent = Marisa::Agent.new
      @agent.set_query(@prefix)
    end

    def each(&block)
      reset_agent
      if block_given?
        # Yield each string in alphabetical order
        yield @agent.key_str while @trie.trie.predictive_search(@agent)
      else
        to_enum(&block)
      end
    end

    def size
      keys.size
    end

    def keys
      @keys ||= [].tap do |arr|
        reset_agent
        arr << @agent.key_str while @trie.trie.predictive_search(@agent)
      end
    end

    def has_keys?
      reset_agent
      return @trie.trie.predictive_search(@agent)
    end

    def include?(key)
      a = Marisa::Agent.new
      a.set_query(key)
      @trie.trie.lookup(a)
    end

    def with_prefixes(&block)
      reset_agent
      while @trie.trie.common_prefix_search(@agent)
        block.call(@agent.key_str)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
melisa-0.2.5 lib/melisa/search.rb
melisa-0.2.4 lib/melisa/search.rb
melisa-0.2.3 lib/melisa/search.rb
melisa-0.2.2 lib/melisa/search.rb