Sha256: a3bb929df6031660baa63a00f271dae2ff88bf1611a246fe3ea2e94274413933

Contents?: true

Size: 1.06 KB

Versions: 3

Compression:

Stored size: 1.06 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
      # Yield each key
      yield @agent.key_str while @trie.trie.predictive_search(@agent)
    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

3 entries across 3 versions & 1 rubygems

Version Path
melisa-0.2.1 lib/melisa/search.rb
melisa-0.2.0 lib/melisa/search.rb
melisa-0.1.0 lib/melisa/search.rb