Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- final class ExtremeSportsTermsModel: CustomStringConvertible {
- let term: String
- var description: String {
- return term
- }
- init(term: String) {
- self.term = term
- }
- }
- final class RelatedFlipsRepository {
- enum Action {
- case add
- case remove
- }
- private var relations: [String: Set<String>] = [:]
- var flips: [ExtremeSportsTermsModel] = []
- init(flips: [ExtremeSportsTermsModel]) {
- self.flips = flips
- }
- // MARK: - Public
- func addFlip(_ flip: ExtremeSportsTermsModel, relatedTo related: [ExtremeSportsTermsModel] = []) {
- if !flips.contains(where: { $0.term == flip.term }) {
- flips.append(flip)
- }
- configureRelated(related, flip: flip, action: .add)
- }
- func getRelated(to flip: ExtremeSportsTermsModel) -> [ExtremeSportsTermsModel] {
- guard let values = relations[flip.term], !values.isEmpty else { return [] }
- return flips.filter({ values.contains($0.term) })
- }
- func configureRelated(_ related: [ExtremeSportsTermsModel], flip: ExtremeSportsTermsModel, action: Action) {
- switch action {
- case .add:
- addRelated(related, to: flip)
- related.forEach({ addRelated([flip], to: $0) })
- case .remove:
- removeRelated(related, from: flip)
- related.forEach({ removeRelated([flip], from: $0) })
- }
- }
- // MARK: - Private
- private func addRelated(_ related: [ExtremeSportsTermsModel], to flip: ExtremeSportsTermsModel) {
- if !related.isEmpty {
- let relatedValues = related.map({ $0.term })
- if let values = relations[flip.term] {
- relations[flip.term] = values.union(relatedValues)
- } else {
- relations[flip.term] = Set(relatedValues)
- }
- }
- }
- private func removeRelated(_ related: [ExtremeSportsTermsModel], from flip: ExtremeSportsTermsModel) {
- guard let values = relations[flip.term], !related.isEmpty else { return }
- relations[flip.term] = values.subtracting(related.map({ $0.term }))
- }
- }
- let ollie = ExtremeSportsTermsModel(term: "Ollie")
- let shuvit = ExtremeSportsTermsModel(term: "Shuvit")
- let acidDrop = ExtremeSportsTermsModel(term: "Acid Drop")
- let repository = RelatedFlipsRepository(flips: [ollie, shuvit, acidDrop])
- repository.configureRelated([acidDrop, shuvit], flip: ollie, action: .add)
- print(repository.getRelated(to: ollie)) // [Shuvit, Acid Drop]
- print(repository.getRelated(to: acidDrop)) // [Ollie]
- repository.configureRelated([acidDrop], flip: ollie, action: .remove)
- print(repository.getRelated(to: ollie)) // [Shuvit]
- print(repository.getRelated(to: acidDrop)) // []
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement