OSDN Git Service

ApplicationDirecroriesの中のアプリケーションに依存する部分を分離した
[kcd/KCD.git] / KCD / ArrayExtensions.swift
1 //
2 //  ArrayExtensions.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/03/01.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10
11 // powered by http://stackoverflow.com/questions/40579554/how-to-display-unique-elements-of-an-array-using-swift
12 extension Sequence where Iterator.Element: Hashable {
13     
14     func unique() -> [Iterator.Element] {
15         
16         var alreadyAdded = Set<Iterator.Element>()
17         
18         return filter {
19             
20             if alreadyAdded.contains($0) {
21                 
22                 return false
23             }
24             
25             alreadyAdded.insert($0)
26             
27             return true
28         }
29     }
30 }
31
32 extension Array {
33     
34     func appended(_ elem: () -> Element) -> Array {
35         
36         return self + [elem()]
37     }
38 }
39
40 infix operator ==? : ComparisonPrecedence
41 func ==? <T: Comparable> (lhv: T, rhv: T) -> ComparisonResult {
42     
43     if lhv == rhv {
44         
45         return .orderedSame
46     }
47     if lhv < rhv {
48         
49         return .orderedAscending
50     }
51     
52     return .orderedDescending
53 }
54
55 extension MutableCollection {
56     
57     private func bsearch(min: Int, max: Int, comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
58         
59         if max < min {
60             
61             return nil
62         }
63         
64         let current = min + (max - min) / 2
65         let v = self[self.index(self.startIndex, offsetBy: current)]
66         let compRes = comparator(v)
67         
68         if compRes == .orderedSame {
69             
70             return v
71         }
72         
73         let newMin = (compRes == .orderedAscending) ? current + 1 : min
74         let newMax = (compRes == .orderedDescending) ? current - 1 : max
75         
76         return bsearch(min: newMin, max: newMax, comparator: comparator)
77     }
78     
79     func binarySearch(comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
80         
81         return bsearch(min: 0, max: self.count - 1, comparator: comparator)
82     }
83 }