Array extension providing support for specifying a Custom Sort implementation with live updates of swapped indices

Home   »   Array extension providing support for specifying a Custom Sort implementation with live updates of swapped indices

//---------------------
//SORTER IMPLEMENTATION:

protocol Sorter {
    typealias OrderingHandler = (Element, Element) throws -> Bool
    func sort(_ array: inout [Element], by areInIncreasingOrder: OrderingHandler) rethrows
}

extension Array {
    mutating func sort(using sorter: Sorter, by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows {
        try sorter.sort(&self, by: areInIncreasingOrder)
    }
    
    func sorted(using sorter: Sorter, by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element] {
        var array = self
        try array.sort(using: sorter, by: areInIncreasingOrder)
        return array
    }
}

protocol SorterPositionObserver {
    typealias PositionUpdateHandler = (_ fromIndex: Int, _ toIndex: Int) -> Void
    
    var positionUpdates: PositionUpdateHandler? { get set }
    func withPositionUpdates(_ handler: @escaping PositionUpdateHandler) -> Self
}

//-------------
//USAGE EXAMPLE:
class BubbleSort: Sorter, SorterPositionObserver {

    var positionUpdates: PositionUpdateHandler?
    
    func withPositionUpdates(_ handler: @escaping PositionUpdateHandler) -> Self {
        self.positionUpdates = handler
        return self
    }
    
    func sort(_ array: inout [Element], by areInIncreasingOrder: OrderingHandler) rethrows {
        for i in 0..)

//Sorted Approach
[5,4,10,1,6,2].sorted(using: BubbleSort()
                        .withPositionUpdates({ i, j in
                            print("swapped from \(i) to \(j)")
                        }),
                      by: >)

Leave a Reply

Your email address will not be published. Required fields are marked *