184 lines
5.6 KiB
Swift
184 lines
5.6 KiB
Swift
import Foundation
|
|
import Units
|
|
|
|
@dynamicMemberLookup
|
|
public struct Nutriments: Codable, Sendable, Sequence {
|
|
// We separate values (Doubles) and units (Strings) for efficient, thread-safe storage
|
|
private let values: [String: Double]
|
|
private let units: [String: String]
|
|
|
|
public init(from decoder: Decoder) throws {
|
|
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
|
var v = [String: Double]()
|
|
var u = [String: String]()
|
|
|
|
for key in container.allKeys {
|
|
let keyStr = key.stringValue
|
|
|
|
// Try decoding as Double first (most common for _100g, _serving)
|
|
if let doubleVal = try? container.decode(Double.self, forKey: key) {
|
|
v[keyStr] = doubleVal
|
|
}
|
|
// Try decoding as String (could be a unit OR a number in string format)
|
|
else if let stringVal = try? container.decode(
|
|
String.self, forKey: key)
|
|
{
|
|
if let doubleFromStr = Double(stringVal) {
|
|
v[keyStr] = doubleFromStr
|
|
} else {
|
|
u[keyStr] = stringVal // It's likely a unit like "kcal", "g", "kj"
|
|
}
|
|
}
|
|
}
|
|
self.values = v
|
|
self.units = u
|
|
}
|
|
|
|
public func encode(to encoder: Encoder) throws {
|
|
var container = encoder.container(keyedBy: AnyCodingKey.self)
|
|
for (key, val) in values {
|
|
try container.encode(val, forKey: AnyCodingKey(stringValue: key))
|
|
}
|
|
for (key, unit) in units {
|
|
try container.encode(unit, forKey: AnyCodingKey(stringValue: key))
|
|
}
|
|
}
|
|
|
|
/// Dynamic lookup: converts `nutriments.energyKcal` -> `Nutrient(name: "energy-kcal")`
|
|
public subscript(dynamicMember member: String) -> Nutrient {
|
|
let kebabName = member.camelCaseToKebabCase()
|
|
return Nutrient(name: kebabName, values: values, units: units)
|
|
}
|
|
|
|
// MARK: - Sequence Conformance
|
|
// Allows: nutriments.forEach { nutrient in ... }
|
|
public func makeIterator() -> AnyIterator<Nutrient> {
|
|
// 1. Collect all keys from values and units
|
|
let allKeys = Set(values.keys).union(units.keys)
|
|
|
|
// 2. Extract unique base names (e.g., "energy-kcal_100g" -> "energy-kcal")
|
|
let baseNames = allKeys.compactMap { key -> String? in
|
|
// Filter out keys that are not nutrient properties
|
|
guard !key.isEmpty else { return nil }
|
|
|
|
// Remove common suffixes to find the "root" nutrient name
|
|
let suffixes = [
|
|
"_100g", "_serving", "_unit", "_value", "_prepared", "_label",
|
|
]
|
|
var name = key
|
|
|
|
// Sort suffixes by length (descending) to avoid partial matches
|
|
for suffix in suffixes {
|
|
if let range = name.range(of: suffix) {
|
|
name.removeSubrange(range)
|
|
}
|
|
}
|
|
return name
|
|
}
|
|
|
|
// 3. Create a unique sorted list
|
|
let uniqueNames = Set(baseNames).sorted()
|
|
var iterator = uniqueNames.makeIterator()
|
|
|
|
// 4. Return an iterator that produces `Nutrient` views
|
|
return AnyIterator {
|
|
guard let name = iterator.next() else { return nil }
|
|
return Nutrient(name: name, values: self.values, units: self.units)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Nutrient View
|
|
public struct Nutrient: Sendable {
|
|
public let name: String
|
|
private let values: [String: Double]
|
|
private let units: [String: String]
|
|
|
|
internal init(
|
|
name: String, values: [String: Double], units: [String: String]
|
|
) {
|
|
self.name = name
|
|
self.values = values
|
|
self.units = units
|
|
}
|
|
|
|
// MARK: - Raw Properties (Mapped to V2 JSON keys)
|
|
public var per100g: Double? { values["\(name)_100g"] }
|
|
public var perServing: Double? { values["\(name)_serving"] }
|
|
public var value: Double? { values["\(name)_value"] ?? values[name] }
|
|
public var unit: String? { units["\(name)_unit"] }
|
|
|
|
// Computed / Legacy
|
|
public var valueComputed: Double? { values["\(name)_value"] }
|
|
|
|
// Prepared
|
|
public var preparedPer100g: Double? { values["\(name)_prepared_100g"] }
|
|
public var preparedPerServing: Double? {
|
|
values["\(name)_prepared_serving"]
|
|
}
|
|
public var preparedValue: Double? {
|
|
values["\(name)_prepared_value"] ?? values["\(name)_prepared"]
|
|
}
|
|
public var preparedUnit: String? { units["\(name)_prepared_unit"] }
|
|
public var preparedValueComputed: Double? {
|
|
values["\(name)_prepared_value"]
|
|
}
|
|
|
|
// MARK: - UnitValue Helpers (Restored)
|
|
|
|
public var per100gUnitValue: UnitValue<Double>? {
|
|
guard let rawValue = per100g ?? value ?? valueComputed,
|
|
let unitString = unit,
|
|
let unitEnum = Unit(rawValue: unitString)
|
|
else { return nil }
|
|
return UnitValue(value: rawValue, unit: unitEnum)
|
|
}
|
|
|
|
public var perServingUnitValue: UnitValue<Double>? {
|
|
guard let rawValue = perServing,
|
|
let unitString = unit,
|
|
let unitEnum = Unit(rawValue: unitString)
|
|
else { return nil }
|
|
return UnitValue(value: rawValue, unit: unitEnum)
|
|
}
|
|
|
|
public var preparedPer100gUnitValue: UnitValue<Double>? {
|
|
guard
|
|
let rawValue = preparedPer100g ?? preparedValue
|
|
?? preparedValueComputed,
|
|
let unitString = preparedUnit ?? unit, // Fallback to main unit
|
|
let unitEnum = Unit(rawValue: unitString)
|
|
else { return nil }
|
|
return UnitValue(value: rawValue, unit: unitEnum)
|
|
}
|
|
|
|
public var preparedPerServingUnitValue: UnitValue<Double>? {
|
|
guard let rawValue = preparedPerServing,
|
|
let unitString = preparedUnit ?? unit,
|
|
let unitEnum = Unit(rawValue: unitString)
|
|
else { return nil }
|
|
return UnitValue(value: rawValue, unit: unitEnum)
|
|
}
|
|
}
|
|
|
|
// MARK: - Helpers
|
|
|
|
private struct AnyCodingKey: CodingKey {
|
|
var stringValue: String
|
|
var intValue: Int?
|
|
init(stringValue: String) { self.stringValue = stringValue }
|
|
init?(intValue: Int) { return nil }
|
|
}
|
|
|
|
extension String {
|
|
// Converts "energyKcal" -> "energy-kcal"
|
|
fileprivate func camelCaseToKebabCase() -> String {
|
|
let pattern = "([a-z0-9])([A-Z])"
|
|
let regex = try! NSRegularExpression(pattern: pattern, options: [])
|
|
let range = NSRange(location: 0, length: self.count)
|
|
return regex.stringByReplacingMatches(
|
|
in: self, options: [], range: range, withTemplate: "$1-$2"
|
|
).lowercased()
|
|
}
|
|
}
|