Skip to content

Commit

Permalink
Merge pull request #12 from amdirent/master
Browse files Browse the repository at this point in the history
Add support for exponent operator and floats
  • Loading branch information
bhgames authored Mar 27, 2019
2 parents 4dd6910 + 875caa3 commit 10070ce
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 9 deletions.
19 changes: 10 additions & 9 deletions lib/json_logic/operation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,18 @@ class Operation
result.nil? ? v.last : result
},
'?:' => ->(v, d) { LAMBDAS['if'].call(v, d) },
'>' => ->(v, d) { v.map(&:to_i).each_cons(2).all? { |i, j| i > j } },
'>=' => ->(v, d) { v.map(&:to_i).each_cons(2).all? { |i, j| i >= j } },
'<' => ->(v, d) { v.map(&:to_i).each_cons(2).all? { |i, j| i < j } },
'<=' => ->(v, d) { v.map(&:to_i).each_cons(2).all? { |i, j| i <= j } },
'max' => ->(v, d) { v.map(&:to_i).max },
'min' => ->(v, d) { v.map(&:to_i).min },
'+' => ->(v, d) { v.map(&:to_i).reduce(:+) },
'-' => ->(v, d) { v.map!(&:to_i); v.size == 1 ? -v.first : v.reduce(:-) },
'*' => ->(v, d) { v.map(&:to_i).reduce(:*) },
'>' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i > j } },
'>=' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i >= j } },
'<' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i < j } },
'<=' => ->(v, d) { v.map(&:to_f).each_cons(2).all? { |i, j| i <= j } },
'max' => ->(v, d) { v.map(&:to_f).max },
'min' => ->(v, d) { v.map(&:to_f).min },
'+' => ->(v, d) { v.map(&:to_f).reduce(:+) },
'-' => ->(v, d) { v.map!(&:to_f); v.size == 1 ? -v.first : v.reduce(:-) },
'*' => ->(v, d) { v.map(&:to_f).reduce(:*) },
'/' => ->(v, d) { v.map(&:to_f).reduce(:/) },
'%' => ->(v, d) { v.map(&:to_i).reduce(:%) },
'^' => ->(v, d) { v.map(&:to_f).reduce(:**) },
'merge' => ->(v, d) { v.flatten },
'in' => ->(v, d) { v[1].include? v[0] },
'cat' => ->(v, d) { v.map(&:to_s).join },
Expand Down
6 changes: 6 additions & 0 deletions lib/json_logic/truthy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ def falsy?
end
end

class Float
def falsy?
zero?
end
end

class Array
def falsy?
empty?
Expand Down
11 changes: 11 additions & 0 deletions test/json_logic_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ def test_add_operation
assert_equal([6], JSONLogic.apply(rules, data))
end

def test_exponent_operation
exp = JSON.parse(%Q|{"^": [{"var": "num"}, 3]}|)
data1 = JSON.parse(%Q|{"num": 2}|)
data2 = JSON.parse(%Q|{"num": 3}|)
data3 = JSON.parse(%Q|{"num": 4}|)

assert_equal(8, JSONLogic.apply(exp, data1).to_i)
assert_equal(27, JSONLogic.apply(exp, data2).to_i)
assert_equal(64, JSONLogic.apply(exp, data3).to_i)
end

def test_array_with_logic
assert_equal [1, 2, 3], JSONLogic.apply([1, {"var" => "x"}, 3], {"x" => 2})

Expand Down

0 comments on commit 10070ce

Please sign in to comment.