update Directory, Fountain, JSReflection, SOAP, XMLRPC to use baskets and new JS...
[org.ibex.js.git] / src / org / ibex / js / JSNumber.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.js;
6
7 abstract class JSNumber extends JSPrimitive {
8     boolean jsequals(JS o) {
9         if(o == this) return true;
10         if(o instanceof JSNumber) {
11             JSNumber n = (JSNumber) o;
12             if(this instanceof D || n instanceof D) return n.toDouble() == toDouble();
13             return n.toLong() == toLong();
14         } else if(o instanceof JSString) {
15             String s = ((JSString)o).s.trim();
16             try {
17                 if(this instanceof D || s.indexOf('.') != -1) return Double.parseDouble(s) == toDouble();
18                 return Long.parseLong(s) == toLong();
19             } catch(NumberFormatException e) {
20                 return false;
21             }
22         } else {
23             return false;
24         }
25     }
26     // FEATURE: Better hash function? (if d != (int) d then do something double specific)
27     public int hashCode() { return toInt(); }
28     
29     abstract int toInt();
30     long toLong() { return toInt(); }
31     boolean toBoolean() { return toInt() != 0; }
32     double toDouble() { return toLong(); }
33     float toFloat() { return (float) toDouble(); }
34     
35     final static class I extends JSNumber {
36         final int i;
37         I(int i) { this.i = i; }
38         int toInt() { return i; }
39         public String coerceToString() { return Integer.toString(i); }
40     }
41     
42     final static class L extends JSNumber {
43         private final long l;
44         L(long l) { this.l = l; }
45         int toInt() { return (int) l; }
46         long toLong() { return l; }
47         public String coerceToString() { return Long.toString(l); }
48     }
49     
50     final static class D extends JSNumber {
51         private final double d;
52         D(double d) { this.d = d; }
53         int toInt() { return (int) d; }
54         long toLong() { return (long) d; }
55         double toDouble()  { return d; }
56         boolean toBoolean() { return d == d && d != 0.0; }
57         public String coerceToString() { return d == (long) d ? Long.toString((long)d) : Double.toString(d); }
58     }
59     
60     final static class B extends JSNumber {
61         private final boolean b;
62         B(boolean b) { this.b = b; }
63         int toInt() { return b ? 1 : 0; }
64         public String coerceToString() { return b ? "true" : "false"; }
65     }
66 }