Author: Andrews Medina <[email protected]>
Branch: 
Changeset: r386:c11ac659bd1e
Date: 2013-05-15 01:29 -0300
http://bitbucket.org/pypy/lang-js/changeset/c11ac659bd1e/

Log:    implemented [].indexOf and [].forEach

diff --git a/js/builtins/array.py b/js/builtins/array.py
--- a/js/builtins/array.py
+++ b/js/builtins/array.py
@@ -40,6 +40,10 @@
     # 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
@@ -162,6 +166,34 @@
         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):
diff --git a/test/test_array.py b/test/test_array.py
--- a/test/test_array.py
+++ b/test/test_array.py
@@ -1,6 +1,18 @@
 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)
_______________________________________________
pypy-commit mailing list
[email protected]
http://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to