damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

InsertSort.swift (1994B)


      1 //
      2 //  InsertSort.swift
      3 //  damus
      4 //
      5 //  Created by William Casarin on 2022-05-09.
      6 //
      7 
      8 import Foundation
      9 
     10 func insert_uniq_sorted_zap(zaps: inout [Zapping], new_zap: Zapping, cmp: (Zapping, Zapping) -> Bool) -> Bool {
     11     var i: Int = 0
     12     
     13     for zap in zaps {
     14         if new_zap.request.ev.id == zap.request.ev.id {
     15             // replace pending
     16             if !new_zap.is_pending && zap.is_pending {
     17                 print("nwc: replacing pending with real zap \(new_zap.request.ev.id)")
     18                 zaps[i] = new_zap
     19                 return true
     20             }
     21             // don't insert duplicate events
     22             return false
     23         }
     24         
     25         if cmp(new_zap, zap)  {
     26             zaps.insert(new_zap, at: i)
     27             return true
     28         }
     29         i += 1
     30     }
     31     
     32     zaps.append(new_zap)
     33     return true
     34 }
     35 
     36 @discardableResult
     37 func insert_uniq_sorted_zap_by_created(zaps: inout [Zapping], new_zap: Zapping) -> Bool {
     38     return insert_uniq_sorted_zap(zaps: &zaps, new_zap: new_zap) { (a, b) in
     39         a.created_at > b.created_at
     40     }
     41 }
     42 
     43 @discardableResult
     44 func insert_uniq_sorted_zap_by_amount(zaps: inout [Zapping], new_zap: Zapping) -> Bool {
     45     return insert_uniq_sorted_zap(zaps: &zaps, new_zap: new_zap) { (a, b) in
     46         a.amount > b.amount
     47     }
     48 }
     49 
     50 func insert_uniq_sorted_event_created(events: inout [NostrEvent], new_ev: NostrEvent) -> Bool {
     51     return insert_uniq_sorted_event(events: &events, new_ev: new_ev) {
     52         $0.created_at > $1.created_at
     53     }
     54 }
     55 
     56 @discardableResult
     57 func insert_uniq_sorted_event(events: inout [NostrEvent], new_ev: NostrEvent, cmp: (NostrEvent, NostrEvent) -> Bool) -> Bool {
     58     var i: Int = 0
     59     
     60     for event in events {
     61         // don't insert duplicate events
     62         if new_ev.id == event.id {
     63             return false
     64         }
     65         
     66         if cmp(new_ev, event) {
     67             events.insert(new_ev, at: i)
     68             return true
     69         }
     70         i += 1
     71     }
     72     
     73     events.append(new_ev)
     74     return true
     75 }