01: package gnu.ecmascript;
02:
03: public class Convert {
04: public static double toNumber(Object x) {
05: if (x instanceof java.lang.Number)
06: return ((java.lang.Number) x).doubleValue();
07: //if (x == ECMAScript.UNDEFINED) return Double.NaN;
08: // if (x == ECMAScript.NULL) return 0;
09: if (x instanceof Boolean)
10: return ((Boolean) x).booleanValue() ? 1 : 0;
11: if (x instanceof String) {
12: try {
13: // FIXME - is Java grammar correct for ECMAScript?
14: return Double.valueOf((String) x).doubleValue();
15: } catch (NumberFormatException ex) {
16: return Double.NaN;
17: }
18: }
19: // if (x instanceof JSObject) { FIXME }
20: return Double.NaN;
21: }
22:
23: public static double toInteger(double x) {
24: if (Double.isNaN(x))
25: return 0.0;
26: return x < 0.0 ? Math.ceil(x) : Math.floor(x);
27: }
28:
29: public static double toInteger(Object x) {
30: return toInteger(toNumber(x));
31: }
32:
33: public int toInt32(double x) {
34: if (Double.isNaN(x) || Double.isInfinite(x))
35: return 0;
36: // FIXME - does not handle overflow correctly!
37: return (int) x;
38: }
39:
40: public int toInt32(Object x) {
41: return toInt32(toNumber(x));
42: }
43: }
|