2003/06/16 07:58:56
[org.ibex.core.git] / src / org / xwt / js / ArrayImpl.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL] 
2
3 package org.xwt.js; 
4 import org.xwt.util.*; 
5 import java.io.*;
6 import java.util.*;
7
8 /** A JavaScript Array */
9 class ArrayImpl extends JS.Obj {
10     private Vec vec = new Vec();
11     public ArrayImpl() { }
12     public ArrayImpl(int size) { vec.setSize(size); }
13     private static int intVal(Object o) {
14         if (o instanceof Number) {
15             int intVal = ((Number)o).intValue();
16             if (intVal == ((Number)o).doubleValue()) return intVal;
17             return Integer.MIN_VALUE;
18         }
19         if (!(o instanceof String)) return Integer.MIN_VALUE;
20         String s = (String)o;
21         for(int i=0; i<s.length(); i++) if (s.charAt(i) < '0' || s.charAt(i) > '9') return Integer.MIN_VALUE;
22         return Integer.parseInt(s);
23     }
24     public Object get(Object key) throws JS.Exn {
25         // FIXME: HACK!
26         if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
27         if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
28         if (key.equals("length")) return new Long(vec.size());
29         int i = intVal(key);
30         if (i == Integer.MIN_VALUE) return super.get(key);
31         try {
32             return vec.elementAt(i);
33         } catch (ArrayIndexOutOfBoundsException e) {
34             return null;
35         }
36     }
37     public void put(Object key, Object val) {
38         if (key.equals("length")) vec.setSize(toNumber(val).intValue());
39         int i = intVal(key);
40         if (i == Integer.MIN_VALUE) super.put(key, val);
41         else {
42             if (i >= vec.size()) vec.setSize(i+1);
43             vec.setElementAt(val, i);
44         }
45     }
46     public Object[] keys() {
47         Object[] sup = super.keys();
48         Object[] ret = new Object[vec.size() + 1 + sup.length];
49         System.arraycopy(sup, 0, ret, vec.size(), sup.length);
50         for(int i=0; i<vec.size(); i++) ret[i] = new Integer(i);
51         ret[vec.size()] = "length";
52         return ret;
53     }
54     public void setSize(int i) { vec.setSize(i); }
55     public int length() { return vec.size(); }
56     public Object elementAt(int i) { return vec.elementAt(i); }
57     public void addElement(Object o) { vec.addElement(o); }
58     public void setElementAt(Object o, int i) { vec.setElementAt(o, i); }
59 }
60