Skip to content

Commit fd8d7d9

Browse files
Add JSArray class to iterate the value
1 parent d0aaa49 commit fd8d7d9

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Sources/JavaScriptKit/JSArray.swift

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
public class JSArray {
3+
4+
static let classObject = JSObjectRef.global.Array.object!
5+
6+
static func isArray(_ object: JSObjectRef) -> Bool {
7+
classObject.isArray.function!(object).boolean!
8+
}
9+
10+
let ref: JSObjectRef
11+
12+
public init?(_ ref: JSObjectRef) {
13+
guard Self.isArray(ref) else { return nil }
14+
self.ref = ref
15+
}
16+
}
17+
18+
19+
extension JSArray: Sequence {
20+
public typealias Element = JSValue
21+
22+
public func makeIterator() -> Iterator {
23+
Iterator(ref: ref)
24+
}
25+
26+
public class Iterator: IteratorProtocol {
27+
let ref: JSObjectRef
28+
var index = 0
29+
init(ref: JSObjectRef) {
30+
self.ref = ref
31+
}
32+
public func next() -> Element? {
33+
defer { index += 1 }
34+
guard index < ref.length.number! else {
35+
return nil
36+
}
37+
let value = ref.get(index)
38+
return value.isNull ? nil : value
39+
}
40+
}
41+
}

Sources/JavaScriptKit/JSValue.swift

+3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ public enum JSValue: Equatable {
3434
default: return nil
3535
}
3636
}
37+
public var array: JSArray? {
38+
object.flatMap { JSArray($0) }
39+
}
3740
public var isNull: Bool { return self == .null }
3841
public var isUndefined: Bool { return self == .undefined }
3942
public var function: JSFunctionRef? {

0 commit comments

Comments
 (0)