Skip to content
This repository has been archived by the owner on May 13, 2019. It is now read-only.

Commit

Permalink
Comparison operators treat null/true/false as 0/1/0.
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewd committed Dec 10, 2010
1 parent 84267b1 commit 7f408e8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
28 changes: 21 additions & 7 deletions lib/capuchin/kernel.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions lib/capuchin/visitor.rb
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 7f408e8

Please sign in to comment.