Skip to content

Commit 933fcc2

Browse files
author
Kenneth Geerts
committed
Add filter method
1 parent 9ebf4b3 commit 933fcc2

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

lib/json_logic.rb

+10-6
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,16 @@
44

55
module JSONLogic
66
def self.apply(logic, data)
7-
return logic unless logic.is_a?(Hash) # pass-thru
8-
operator, values = logic.first # unwrap single-key hash
9-
values = [values] unless values.is_a?(Array) # syntactic sugar
10-
values.map! { |value| apply(value, data) } # recursion step
11-
values.flatten!(1) if values.size == 1 # [['A']] => ['A']
12-
Operation.perform(operator, values, data || {}) # perform operation
7+
return logic unless logic.is_a?(Hash) # pass-thru
8+
operator, values = logic.first # unwrap single-key hash
9+
values = [values] unless values.is_a?(Array) # syntactic sugar
10+
new_vals = values.map { |value| apply(value, data) } # recursion step
11+
new_vals.flatten!(1) if new_vals.size == 1 # [['A']] => ['A']
12+
Operation.perform(operator, new_vals, data || {}) # perform operation
13+
end
14+
15+
def self.filter(logic, data)
16+
data.select { |d| apply(logic, d) }
1317
end
1418
end
1519

test/json_logic_test.rb

+6
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,10 @@ class JSONLogicTest < Minitest::Test
1919
end
2020
count += 1
2121
end
22+
23+
def test_filter
24+
filter = JSON.parse(%Q|{">": [{"var": "id"}, 1]}|)
25+
data = JSON.parse(%Q|[{"id": 1},{"id": 2}]|)
26+
assert_equal([{'id' => 2}], JSONLogic.filter(filter, data))
27+
end
2228
end

0 commit comments

Comments
 (0)