Sha256: fdd350bf8d48a568997ce3157ccd4794a801e233210bea6e74c7c91c05351949

Contents?: true

Size: 1.14 KB

Versions: 3

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

module Basic101

  class UserDefinedFunction < Function

    include Identity

    def initialize(identifier, parameters, expression)
      @identifier = identifier
      @parameters = parameters
      @expression = expression
    end

    def name
      @identifier.to_s
    end

    def call(runtime, args)
      raise InvalidArgumentError unless args.size == @parameters.size
      save_parameters(runtime)
      bind_arguments(runtime, args)
      result = @expression.eval(runtime)
      restore_parameters(runtime)
      result
    end

    protected

    def state
      [@identifier, @parameters, @expression]
    end

    private

    def save_parameters(runtime)
      @original_parameter_values = @parameters.map do |parameter|
        parameter.eval(runtime)
      end
    end

    def bind_arguments(runtime, args)
      @parameters.zip(args).each do |parameter, arg|
        parameter.assign(runtime, arg.eval(runtime))
      end
    end

    def restore_parameters(runtime)
      @parameters.zip(@original_parameter_values) do |parameter, value|
        parameter.assign(runtime, value)
      end
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
basic101-1.0.2 lib/basic101/user_defined_function.rb
basic101-1.0.1 lib/basic101/user_defined_function.rb
basic101-1.0.0 lib/basic101/user_defined_function.rb