JS backend: added dynamic.iterator to simplify the using "iterable" objects.

This commit is contained in:
Zalim Bashorov
2014-12-16 16:05:38 +03:00
parent f4b96a0a1a
commit d666677958
3 changed files with 70 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
/*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.js
// TODO add the support ES6 iterators
public fun dynamic.iterator(): Iterator<dynamic> {
val r = this
return when {
this["iterator"] != null ->
this["iterator"]()
js("Array.isArray(r)") ->
(this: Array<*>).iterator()
else ->
(r: Iterable<*>).iterator()
}
}
@@ -120,6 +120,12 @@ public class DynamicTestGenerated extends AbstractDynamicTest {
doTest(fileName);
}
@TestMetadata("iterator.kt")
public void testIterator() throws Exception {
String fileName = JetTestUtils.navigationMetadata("js/js.translator/testData/dynamic/cases/iterator.kt");
doTest(fileName);
}
@TestMetadata("nameClashing.kt")
public void testNameClashing() throws Exception {
String fileName = JetTestUtils.navigationMetadata("js/js.translator/testData/dynamic/cases/nameClashing.kt");
@@ -0,0 +1,32 @@
package foo
fun testFor(expected: Int, d: dynamic, case: String) {
var actual = 0
for (v in d) {
actual += v: Int
}
assertEquals(expected, actual, "testFor on $case")
}
fun testIterator(expected: Int, d: dynamic, case: String) {
var actual = 0
val it = d.iterator()
while (it.hasNext()) {
actual += it.next(): Int
}
assertEquals(expected, actual, "testIterator on $case")
}
fun test(expected: Int, d: dynamic, case: String) {
testFor(expected, d, case)
testIterator(expected, d, case)
}
fun box(): String {
test(6, array(1, 2, 3), "array")
test(64, byteArray(42, 22), "byte array")
test(66, listOf(55, 3, 8), "list")
test(167, setOf(55, 3, 8, 101), "set")
return "OK"
}