From 0f9cd7f8747f2cc0d21dab04c23170bcad254a91 Mon Sep 17 00:00:00 2001 From: nixzhu Date: Mon, 19 Aug 2024 10:01:43 +0800 Subject: [PATCH] AnandaJSON withValueExtractor --- Sources/Ananda/AnandaJSON.swift | 8 ++++++ Sources/Ananda/AnandaValueExtractor.swift | 8 ++---- Tests/AnandaTests/AnandaTests.swift | 33 +++-------------------- 3 files changed, 13 insertions(+), 36 deletions(-) diff --git a/Sources/Ananda/AnandaJSON.swift b/Sources/Ananda/AnandaJSON.swift index 750bafb..9259a46 100644 --- a/Sources/Ananda/AnandaJSON.swift +++ b/Sources/Ananda/AnandaJSON.swift @@ -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] diff --git a/Sources/Ananda/AnandaValueExtractor.swift b/Sources/Ananda/AnandaValueExtractor.swift index d110584..cf634f4 100644 --- a/Sources/Ananda/AnandaValueExtractor.swift +++ b/Sources/Ananda/AnandaValueExtractor.swift @@ -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) } diff --git a/Tests/AnandaTests/AnandaTests.swift b/Tests/AnandaTests/AnandaTests.swift index 501bfe6..1b0dfdc 100644 --- a/Tests/AnandaTests/AnandaTests.swift +++ b/Tests/AnandaTests/AnandaTests.swift @@ -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 } @@ -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() @@ -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