Swiftpack.co - Package - SoftwareEngineerChris/Consolidate

Consolidate

Build Status Docs SPM

Installation

Swift Package Manager

dependencies: [
   .package(url: "https://github.com/SoftwareEngineerChris/Consolidate.git", from: "1.0.0")
]

Usage Example

Using KeyPath

let allTaxes = [
    TaxAmount(name: "Import Tax", amount: 3.00),
    TaxAmount(name: "Sales Tax", amount: 1.75),
    TaxAmount(name: "Import Tax", amount: 2.30)
]

let consolidatedTaxes = allTaxes.consolidated(by: \.name) {
    TaxAmount(tax: $0.name, amount: $0.amount + $1.amount)
}

// Would result in:

let consolidatedTaxes = [
    TaxAmount(name: "Import Tax", amount: 5.30),
    TaxAmount(name: "Sales Tax", amount: 4.10)
]

Using Closures

let allTaxes = [
    TaxAmount(name: "Import Tax", amount: 3.00),
    TaxAmount(name: "Sales Tax", amount: 1.75),
    TaxAmount(name: "Import Tax", amount: 2.30)
]

let consolidatedTaxes = allTaxes.consolidated(by: { $0.name == $1.name }) {
    TaxAmount(tax: $0.name, amount: $0.amount + $1.amount)
}

// Would result in:

 let consolidatedTaxes = [
    TaxAmount(name: "Import Tax", amount: 5.30),
    TaxAmount(name: "Sales Tax", amount: 4.10)
]

Using Consolidatable Protocol

struct TaxAmount: Consolidatable {

    let name: String
    let amount: Decimal

    var consolidationGroup: AnyHashable {
        return name
    }

    func consolidate(with other: Self) -> Self {
        return .init(name: name, amount: amount + other.amount)
    }
}

The above implementation would consolidate like this:

let taxes = [
    TaxAmount(name: "Import Tax", amount: 3.00),
    TaxAmount(name: "Sales Tax", amount: 1.75),
    TaxAmount(name: "Import Tax", amount: 2.30)
].consolidated()

// Results in:

let taxes = [
    TaxAmount(name: "Import Tax", amount: 5.30),
    TaxAmount(name: "Sales Tax", amount: 4.10)
]

Github

link
Stars: 0
Help us keep the lights on

Dependencies