Skip to content

Commit

Permalink
AnandaJSON withValueExtractor
Browse files Browse the repository at this point in the history
  • Loading branch information
nixzhu committed Aug 19, 2024
1 parent ed7d361 commit 0f9cd7f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 36 deletions.
8 changes: 8 additions & 0 deletions Sources/Ananda/AnandaJSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ import yyjson
self.valueExtractor = valueExtractor
}

/// `AnandaJSON` with new `valueExtractor`.
public func withValueExtractor(_ valueExtractor: AnandaValueExtractor) -> AnandaJSON {
.init(
pointer: pointer,
valueExtractor: valueExtractor
)
}

/// Object's member value with`dynamicMember` as key
public subscript(dynamicMember member: String) -> AnandaJSON {
self[member]
Expand Down
8 changes: 2 additions & 6 deletions Sources/Ananda/AnandaValueExtractor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,9 @@ public struct AnandaValueExtractor: Sendable {
}
},
double: @Sendable @escaping (AnandaJSON) -> Double? = {
if let double = $0.originalDouble {
return double
if let number = $0.originalNumber {
return number
} else {
if let int = $0.originalInt {
return Double(int)
}

if let string = $0.originalString {
return Double(string)
}
Expand Down
33 changes: 3 additions & 30 deletions Tests/AnandaTests/AnandaTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -397,11 +397,9 @@ final class AnandaTests: XCTestCase {
}

if let string = $0.originalString {
switch string {
switch string.lowercased() {
case "true":
return true
case "false":
return false
default:
break
}
Expand All @@ -419,6 +417,7 @@ final class AnandaTests: XCTestCase {
let createdAt: Date

init(json: AnandaJSON) {
let json = json.withValueExtractor(Self.valueExtractor)
id = json.id.int()
content = json.content.string()
isProtected = json.is_protected.bool()
Expand All @@ -438,36 +437,10 @@ final class AnandaTests: XCTestCase {
assert(json.toots[1].id.int == 2)
assert(json.toots[2].id.int == 88_888_888_888_888_888)
assert(json.toots[3].id.int == 99_999_999_999_999_999)
assert(toots.map { $0.isProtected } == [false, true, false, true])
}
}

static var valueExtractor: AnandaValueExtractor {
.init(
bool: {
if let bool = $0.originalBool {
return bool
} else {
if let int = $0.originalInt {
return int != 0
}

if let string = $0.originalString {
switch string {
case "true":
return true
case "false":
return false
default:
break
}
}

return nil
}
}
)
}

let id: Int
let name: String
let int: Int
Expand Down

0 comments on commit 0f9cd7f

Please sign in to comment.