22e9f2368d9b4195aed2b40409e2bd25ce4817fb
[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 // FIXME: could use some cleaning up...
9
10 /** A JavaScript Array */
11 class ArrayImpl extends JS.Obj {
12     private Vec vec = new Vec();
13     public ArrayImpl() { }
14     public ArrayImpl(int size) { vec.setSize(size); }
15     private static int intVal(Object o) {
16         if (o instanceof Number) {
17             int intVal = ((Number)o).intValue();
18             if (intVal == ((Number)o).doubleValue()) return intVal;
19             return Integer.MIN_VALUE;
20         }
21         if (!(o instanceof String)) return Integer.MIN_VALUE;
22         String s = (String)o;
23         for(int i=0; i<s.length(); i++) if (s.charAt(i) < '0' || s.charAt(i) > '9') return Integer.MIN_VALUE;
24         return Integer.parseInt(s);
25     }
26     public Object get(Object key) throws JS.Exn {
27         // FIXME: HACK!
28         if (key.equals("cascade")) return org.xwt.Trap.cascadeFunction;
29         if (key.equals("trapee")) return org.xwt.Trap.currentTrapee();
30         if (key.equals("length")) return new Long(vec.size());
31         int i = intVal(key);
32         if (i == Integer.MIN_VALUE) return super.get(key);
33         try {
34             return vec.elementAt(i);
35         } catch (ArrayIndexOutOfBoundsException e) {
36             return null;
37         }
38     }
39     public void put(Object key, Object val) {
40         if (key.equals("length")) vec.setSize(toNumber(val).intValue());
41         int i = intVal(key);
42         if (i == Integer.MIN_VALUE) super.put(key, val);
43         else {
44             if (i >= vec.size()) vec.setSize(i+1);
45             vec.setElementAt(val, i);
46         }
47     }
48     public Object[] keys() {
49         Object[] sup = super.keys();
50         Object[] ret = new Object[vec.size() + 1 + sup.length];
51         System.arraycopy(sup, 0, ret, vec.size(), sup.length);
52         for(int i=0; i<vec.size(); i++) ret[i] = new Integer(i);
53         ret[vec.size()] = "length";
54         return ret;
55     }
56     public void setSize(int i) { vec.setSize(i); }
57     public int length() { return vec.size(); }
58     public Object elementAt(int i) { return vec.elementAt(i); }
59     public void addElement(Object o) { vec.addElement(o); }
60     public void setElementAt(Object o, int i) { vec.setElementAt(o, i); }
61 }
62