Sha256: 988b90f2a62634e8caacc9d5e806bcf5a7342716dd02e01f5217a752468fe7b1

Contents?: true

Size: 1.37 KB

Versions: 11

Compression:

Stored size: 1.37 KB

Contents

require 'dentaku/evaluator'
require 'dentaku/token'
require 'dentaku/tokenizer'

module Dentaku
  class Calculator
    attr_reader :result

    def initialize
      clear
    end

    def evaluate(expression, data={})
      @tokenizer ||= Tokenizer.new
      @tokens = @tokenizer.tokenize(expression)

      store(data) do
        @evaluator ||= Evaluator.new
        @result = @evaluator.evaluate(replace_identifiers_with_values)
      end
    end

    def memory(key=nil)
      key ? @memory[key.to_sym] : @memory
    end

    def store(key_or_hash, value=nil)
      restore = @memory.dup

      if value
        @memory[key_or_hash.to_sym] = value
      else
        key_or_hash.each do |key, value|
          @memory[key.to_sym] = value if value
        end
      end

      if block_given?
        result = yield
        @memory = restore
        return result
      end

      self
    end
    alias_method :bind, :store

    def clear
      @memory = {}
    end

    def empty?
      @memory.empty?
    end

    private

    def replace_identifiers_with_values
      @tokens.map do |token|
        if token.is?(:identifier)
          value = memory(token.value)
          type  = type_for_value(value)

          Token.new(type, value)
        else
          token
        end
      end
    end

    def type_for_value(value)
      value.is_a?(String) ? :string : :numeric
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
dentaku-0.2.10 lib/dentaku/calculator.rb
dentaku-0.2.9 lib/dentaku/calculator.rb
dentaku-0.2.8 lib/dentaku/calculator.rb
dentaku-0.2.7 lib/dentaku/calculator.rb
dentaku-0.2.6 lib/dentaku/calculator.rb
dentaku-0.2.5 lib/dentaku/calculator.rb
dentaku-0.2.4 lib/dentaku/calculator.rb
dentaku-0.2.3 lib/dentaku/calculator.rb
dentaku-0.2.2 lib/dentaku/calculator.rb
dentaku-0.2.1 lib/dentaku/calculator.rb
dentaku-0.1.3 lib/dentaku/calculator.rb