Skip to content

Commit e0e2517

Browse files
authored
Add Hashable conformance to JSObject (swiftwasm#162)
1 parent 80d4451 commit e0e2517

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

IntegrationTests/TestSuites/Sources/PrimaryTests/UnitTestUtils.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ func expectEqual<T: Equatable>(
3838
}
3939
}
4040

41+
func expectNotEqual<T: Equatable>(
42+
_ lhs: T, _ rhs: T,
43+
file: StaticString = #file, line: UInt = #line, column: UInt = #column
44+
) throws {
45+
if lhs == rhs {
46+
throw MessageError("Expect to not be equal \"\(lhs)\" and \"\(rhs)\"", file: file, line: line, column: column)
47+
}
48+
}
49+
4150
func expectObject(_ value: JSValue, file: StaticString = #file, line: UInt = #line, column: UInt = #column) throws -> JSObject {
4251
switch value {
4352
case let .object(ref): return ref

IntegrationTests/TestSuites/Sources/PrimaryTests/main.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,4 +746,23 @@ try test("Grow Memory") {
746746
try expectEqual(string, jsString.description)
747747
}
748748

749+
try test("Hashable Conformance") {
750+
let globalObject1 = JSObject.global.console.object!
751+
let globalObject2 = JSObject.global.console.object!
752+
try expectEqual(globalObject1.hashValue, globalObject2.hashValue)
753+
// These are 2 different objects in Swift referencing the same object in JavaScript
754+
try expectNotEqual(ObjectIdentifier(globalObject1), ObjectIdentifier(globalObject2))
755+
756+
let sameObjectSet: Set<JSObject> = [globalObject1, globalObject2]
757+
try expectEqual(sameObjectSet.count, 1)
758+
759+
let objectConstructor = JSObject.global.Object.function!
760+
let obj = objectConstructor.new()
761+
obj.a = 1.jsValue()
762+
let firstHash = obj.hashValue
763+
obj.b = 2.jsValue()
764+
let secondHash = obj.hashValue
765+
try expectEqual(firstHash, secondHash)
766+
}
767+
749768
Expectation.wait(expectations)

Sources/JavaScriptKit/FundamentalObjects/JSObject.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,16 @@ extension JSObject: CustomStringConvertible {
135135
public var description: String { self.toString!().string! }
136136
}
137137

138+
extension JSObject: Hashable {
139+
/// Hashes the essential components of this value by feeding them into the
140+
/// given hasher.
141+
///
142+
/// - Parameter hasher: The hasher to use when combining the components
143+
/// of this instance.
144+
public func hash(into hasher: inout Hasher) {
145+
hasher.combine(id)
146+
}
147+
}
138148

139149
/// A `JSObject` wrapper that enables throwing method calls capturing `this`.
140150
/// Exceptions produced by JavaScript functions will be thrown as `JSValue`.

0 commit comments

Comments
 (0)