Permalink
Browse files

Comparison operators treat null/true/false as 0/1/0.

  • Loading branch information...
1 parent 84267b1 commit 7f408e828c0438ffe7622dd0ccea54259d1a6559 @matthewd committed Dec 10, 2010
Showing with 25 additions and 11 deletions.
  1. +21 −7 lib/capuchin/kernel.rb
  2. +4 −4 lib/capuchin/visitor.rb
@@ -133,6 +133,12 @@ def initialize(name=nil, object={}, mod=nil, &block)
end
end
end
+module JSComparable
+ def js_lt(other); self.js_cmp < other.js_cmp; end
+ def js_gt(other); self.js_cmp > other.js_cmp; end
+ def js_lte(other); self.js_cmp <= other.js_cmp; end
+ def js_gte(other); self.js_cmp >= other.js_cmp; end
+end
class Class
def js_new(*args); new(*args); end
def js_instance_of(v); self === v; end
@@ -188,25 +194,23 @@ def self.js_new(*args)
new(*args)
end
end
-class Integer
- def js_div(n); n == 0 ? self.to_f / n : self / n; end
+class Numeric
+ include JSComparable
+ def js_cmp; self; end
+ def js_typeof; 'number'; end
js_def :valueOf do
self
end
end
class Fixnum
+ def js_div(n); (0 == n ? self.to_f : self) / n; end
def js_key; self; end
def js_truthy?; 0 != self; end
- def js_typeof; 'number'; end
end
class Float
- def js_typeof; 'number'; end
js_def :toFixed do |x|
self.to_i
end
- js_def :valueOf do
- self
- end
js_def :toPrecision do |digits|
"%.#{digits}f" % self
end
@@ -215,6 +219,7 @@ class Symbol
def js_key; self; end
end
class String
+ def js_cmp; to_f; end
js_attr :length do
size
end
@@ -227,11 +232,20 @@ def js_truthy?; size > 0; end
def js_typeof; 'string'; end
end
class TrueClass
+ include JSComparable
+ def js_cmp; 1; end
def js_typeof; 'boolean'; end
end
class FalseClass
+ include JSComparable
+ def js_cmp; 0; end
def js_typeof; 'boolean'; end
end
+class NilClass
+ include JSComparable
+ def js_cmp; 0; end
+ def js_div(n); 0.js_div(n); end
+end
class Method
include JSOpen
def js_prototype
@@ -483,8 +483,8 @@ def visit_PostfixNode(o)
[
[ :Add, :js_add, :OpPlusEqual, :meta_send_op_plus ],
[ :Subtract, :-, :OpMinusEqual, :meta_send_op_minus ],
- [ :Greater, :>, nil, :meta_send_op_gt ],
- [ :Less, :<, nil, :meta_send_op_lt ],
+ [ :Greater, :js_gt, nil, :meta_send_op_gt ],
+ [ :Less, :js_lt, nil, :meta_send_op_lt ],
].each do |name,op,eq,meta|
define_method(:"visit_#{name}Node") do |o|
pos(o)
@@ -513,8 +513,8 @@ def visit_PostfixNode(o)
[ :Multiply, :*, :OpMultiplyEqual ],
[ :RightShift, :>>, :OpRShiftEqual ],
[ :UnsignedRightShift, :">>>", :OpURShiftEqual ],
- [ :GreaterOrEqual, :>=, nil ],
- [ :LessOrEqual, :<=, nil ],
+ [ :GreaterOrEqual, :js_gte, nil ],
+ [ :LessOrEqual, :js_lte, nil ],
].each do |name,op,eq|
define_method(:"visit_#{name}Node") do |o|
pos(o)

0 comments on commit 7f408e8

Please sign in to comment.