Skip to content

Commit

Permalink
Allow passing nil in as a variable value
Browse files Browse the repository at this point in the history
This requires moving things around so that nil values are only set to
the nodes' context hash if that value was explicitly set on the
calculator. Previously every referenced variable name would be added as
a key to the context hash even it was unbound.
  • Loading branch information
tristil committed Feb 18, 2016
1 parent 672b65a commit 1058003
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
7 changes: 4 additions & 3 deletions lib/dentaku/ast/identifier.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ def initialize(token)
end

def value(context={})
v = context[identifier]
v = context.fetch(identifier) do
raise UnboundVariableError.new([identifier])
end

case v
when Node
v.value(context)
when NilClass
raise UnboundVariableError.new([identifier])
else
v
end
Expand Down
14 changes: 12 additions & 2 deletions lib/dentaku/bulk_expression_solver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,18 @@ def raise_exception_handler
def load_results(&block)
variables_in_resolve_order.each_with_object({}) do |var_name, r|
begin
r[var_name] = calculator.memory[var_name] ||
evaluate!(expressions[var_name], expressions.merge(r))
value_from_memory = calculator.memory[var_name]

if value_from_memory.nil? &&
expressions[var_name].nil? &&
!calculator.memory.has_key?(var_name)
next
end

value = value_from_memory ||
evaluate!(expressions[var_name], expressions.merge(r))

r[var_name] = value
rescue Dentaku::UnboundVariableError, ZeroDivisionError => ex
r[var_name] = block.call(ex)
end
Expand Down
16 changes: 16 additions & 0 deletions spec/calculator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,22 @@
it 'can be used in IF statements' do
expect(calculator.evaluate('IF(null, 1, 2)')).to eq(2)
end

it 'can be used in IF statements when passed in' do
expect(calculator.evaluate('IF(foo, 1, 2)', foo: nil)).to eq(2)
end

it 'nil values are carried across middle terms' do
results = calculator.solve!(
choice: 'IF(bar, 1, 2)',
bar: 'foo',
foo: nil)
expect(results).to eq(
choice: 2,
bar: nil,
foo: nil
)
end
end

describe 'case statements' do
Expand Down

0 comments on commit 1058003

Please sign in to comment.