dry-rb / dry-logic

Predicate logic with rule composition
https://dry-rb.org/gems/dry-logic/
MIT License
179 stars 66 forks source link

Add numerically predicates. #6

Closed fran-worley closed 8 years ago

fran-worley commented 8 years ago

Fixes #5.

Jury is out on the :number? predicate.

It appears to be quicker to test if ruby can float a string than match a regex.

The downside is that this doesn't cover the edge cases that the regexps in coercible do, and you have rescue potential errors.

What are your thoughts @solnic. Happy to revise.

require "benchmark"

Benchmark.bm(7) do |x|
  x.report("float_conversion:") { (1..10000).each { |i| Float(Random.new.rand(i).to_s) } }
  x.report("regex_conversion:") { (1..10000).each { |i| Regexp.new(/\A[+-]?\d+\Z/).match(Random.new.rand(i).to_s) } }
end

                   user       system     total    real
float_conversion:  0.100000   0.070000   0.170000 (  0.169644)
regex_conversion:  0.200000   0.080000   0.280000 (  0.279153)
solnic commented 8 years ago

Great work. Thank you for your additional effort with benchmarks. Let's use the faster one and see how it goes. We can always easily change it when people report issues about edge cases.