Skip to content

Commit 472132f

Browse files
committed
Implement isObject & object properties
1 parent 9df6998 commit 472132f

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Sources/JavaScript/JSValue.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,26 @@ extension JSValue {
6969
}
7070
}
7171

72+
extension JSValue {
73+
subscript(_ property: String) -> JSValue? {
74+
guard isObject else {
75+
return nil
76+
}
77+
let bytes = [UInt16](property.utf16)
78+
let property = JSStringCreateWithCharacters(bytes, bytes.count)
79+
defer { JSStringRelease(property) }
80+
81+
var exception: JSValueRef? = nil
82+
let result = JSObjectGetProperty(context, pointer, property, &exception)
83+
84+
if exception != nil {
85+
return nil
86+
}
87+
return JSValue(context: context, pointer: result!)
88+
}
89+
}
90+
91+
7292
extension JSValue {
7393
public var isNull: Bool {
7494
return JSValueIsNull(context, pointer)
@@ -89,6 +109,10 @@ extension JSValue {
89109
public var isString: Bool {
90110
return JSValueIsString(context, pointer)
91111
}
112+
113+
public var isObject: Bool {
114+
return JSValueIsObject(context, pointer)
115+
}
92116
}
93117

94118
extension JSValue {

Tests/JavaScriptTests/JSValueTests.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,20 @@ final class JSValueTests: TestCase {
3131
fail(String(describing: error))
3232
}
3333
}
34+
35+
func testProperty() {
36+
do {
37+
let context = JSContext()
38+
let result = try context.evaluate("""
39+
(function(){
40+
return { property: 'test' }
41+
})()
42+
""")
43+
44+
print(result)
45+
assertEqual(try result["property"]?.toString(), "test")
46+
} catch {
47+
fail(String(describing: error))
48+
}
49+
}
3450
}

0 commit comments

Comments
 (0)