vendredi 29 janvier 2021

Sort objects with multiple dynamic else-if statements

Considering we have the following:

typealias Fruit = String
typealias Count = Int

struct Smoothie {
   let uuid: String
   let fruits: [Fruit: Count]
}

let smoothies: [Smoothie] = ...

Given a conditions array set by the user:

let conditions: [Fruit] = ...

The lowest the index in the conditions array, the most important we consider it is for sorting.

I would like to sort the smoothies array so that the smoothies that contain the highest number of fruits (Count) from the conditions array, appear first.

If a fruit doesn't appear in the fruits dictionary, we consider its count as 0.

For example:

let fruitsA = ["Apple": 3, "Mango": 4, "Pear": 8, "Cherry": 1, "Banana": 2]
let smoothieA = Smoothie(uuid: "smoothie_a", fruits: fruitsA)

let fruitsB = ["Apple": 10, "Mango": 9, "Grapes": 8, "Cherry": 9]
let smoothieB = Smoothie(uuid: "smoothie_b", fruits: fruitsB)

let fruitsC = ["Apple": 23, "Kiwi": 4, "Pear": 1, "Cherry": 17, "Banana": 8]
let smoothieC = Smoothie(uuid: "smoothie_c", fruits: fruitsC)

let fruitsD = ["Apple": 1, "Orange": 6, "Pear": 8]
let smoothieD = Smoothie(uuid: "smoothie_d", fruits: fruitsD)

let conditions: [Fruit] = ["Apple", "Banana", "Cherry"]

Should return the following:

let sortedSmoothies = [smoothieC, smoothieB, smoothieA, smoothieD]

Because we're first sorting by Apple, then by Banana, then by Cherry count.

If I knew it would always be about Apple, Banana & Cherry, I could do the following and it would just work:

let sortedSmoothies = smoothies.sorted {
     if $0.fruits["Apple"] != $1.fruits["Apple"] {
         return $0.fruits["Apple"] > $1.fruits["Apple"]
     } else if $0.fruits["Banana"] != $1.fruits["Banana"] {
         return $0.fruits["Banana"] > $1.fruits["Banana"]
     } else {
         return $0.fruits["Cherry"] > $1.fruits["Cherry"]
     }
}

But in my case I do not know what are the fruits (and how many of them) that the user is going to select for filtering in the conditions array.

Does anyone has an idea how to sort this out please?

Thank you!

Aucun commentaire:

Enregistrer un commentaire