Skip to content

Implement RandomAccessCollection on JSArrayRef #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
dist
node_modules
.DS_Store
/.build
.build
/Packages
/*.xcodeproj
xcuserdata/
11 changes: 11 additions & 0 deletions IntegrationTests/TestSuites/Sources/PrimaryTests/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ Array_Iterator: do {
try expectEqual(Array(array), expectedProp_4)
}

Array_RandomAccessCollection: do {
let globalObject1 = getJSValue(this: .global, name: "globalObject1")
let globalObject1Ref = try expectObject(globalObject1)
let prop_4 = getJSValue(this: globalObject1Ref, name: "prop_4")
let array = try expectArray(prop_4)
let expectedProp_4: [JSValue] = [
.number(3), .number(4), .string("str_elm_1"), .number(5),
]
try expectEqual([array[0], array[1], array[2], array[3]], expectedProp_4)
}

Value_Decoder: do {
struct GlobalObject1: Codable {
struct Prop1: Codable {
Expand Down
10 changes: 9 additions & 1 deletion Sources/JavaScriptKit/JSArrayRef.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class JSArrayRef {
}
}

extension JSArrayRef: Sequence {
extension JSArrayRef: RandomAccessCollection {
public typealias Element = JSValue

public func makeIterator() -> Iterator {
Expand All @@ -37,4 +37,12 @@ extension JSArrayRef: Sequence {
return value.isNull ? nil : value
}
}

public subscript(position: Int) -> JSValue {
ref.get(position)
}

public var startIndex: Int { 0 }

public var endIndex: Int { ref.length.number.map(Int.init) ?? 0 }
}