Commits

Andrews Medina committed c11ac65

implemented [].indexOf and [].forEach

Comments (0)

Files changed (2)

js/builtins/array.py

     # 15.4.4.11
     put_native_function(w_ArrayPrototype, u'sort', sort)
 
+    put_native_function(w_ArrayPrototype, u'forEach', for_each)
+
+    put_native_function(w_ArrayPrototype, u'indexOf', index_of)
+
 
 # 15.4.4.7
 @w_return
         lower = lower + 1
 
 
+@w_return
+def index_of(this, args):
+    obj = this
+    length = this.get(u'length').ToUInt32()
+    elem = get_arg(args, 0)
+    from_index = get_arg(args, 1).ToUInt32()
+
+    from js.jsobj import W_IntNumber
+    for i in xrange(from_index, length):
+        y = obj.get(unicode(i))
+        if elem == y:
+            return W_IntNumber(i)
+    return W_IntNumber(-1)
+
+
+def for_each(this, args):
+    obj = this
+    length = this.get(u'length').ToUInt32()
+
+    callback = get_arg(args, 0)
+    from js.jsobj import W_BasicFunction
+    assert isinstance(callback, W_BasicFunction)
+
+    for i in xrange(length):
+        x = obj.get(unicode(str(i)))
+        callback.Call(args=[x], this=newundefined())
+
+
 # 15.4.4.11
 @w_return
 def sort(this, args):

test/test_array.py

 from test.test_interp import assertv, assertp
 
 
+def test_array_index_of(capsys):
+    assertp("var a = [1,2,3]; print(a.indexOf(1));", "0", capsys)
+    assertp("var a = [1,2,3]; print(a.indexOf(3));", "2", capsys)
+    assertp("var a = [1,2,3]; print(a.indexOf(5));", "-1", capsys)
+    assertp("var a = [1,2,3,1]; print(a.indexOf(1,2));", "3", capsys)
+    assertp("var a = [1,2,3,1]; print(a.indexOf(1,5));", "-1", capsys)
+
+
+def test_array_foreach(capsys):
+    assertp("var a = [1,2,3]; var b = []; a.forEach(function(v){b.push(v*2)}); print(b);", "2,4,6", capsys)
+
+
 def test_sort(capsys):
     assertp("var x = [5,2]; print(x.sort());", '2,5', capsys)
     assertp("var x = [1,2,3]; print(x.sort());", '1,2,3', capsys)