Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
jakebromberg / Array+EachCons.swift
Last active May 31, 2022 17:30 — forked from khanlou/Array+EachCons.swift
each_cons from Ruby in Swift as a function on Sequence
extension Collection {
func eachConsecutive(_ size: Int) -> Array<SubSequence> {
let droppedIndices = indices.dropFirst(size - 1)
return zip(indices, droppedIndices)
.map { return self[$0...$1] }
}
}
struct NearestKeyDictionary<Key: Comparable & Hashable, Value: Equatable>: ExpressibleByDictionaryLiteral {
// MARK: Type aliases
typealias Values = Dictionary<Key, Value>.Values
// MARK: Public properties
var allValues: Values {
return dictionary.values
}
// One note before we start: if the inhabitants of Value are a closed set,
// then making Value an enum is going to be a clearer model than using a
// protocol like this. I'm assuming you need to be able to retroactively add
// new members of Value.
// Can't use Equatable directly because of its Self requirement.
protocol HeteroEquatable {
func isEqualTo(_ value: HeteroEquatable) -> Bool
}
protocol Coalescable {
/// - Returns: One of the four cases:
/// - a new, combined instance
/// - nil, signalling the two cannot be combined
/// - `self`
/// - `other`
func coalesce(with other: Self) -> Self?
}
extension Sequence where Element: Coalescable {
extension Sequence {
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>, comparator: (T, T) -> Bool = { $0 < $1 }) -> [Element] {
return sorted(by: { (e1, e2) -> Bool in
return comparator(e1[keyPath: keyPath], e2[keyPath: keyPath])
})
}
}
let names = ["Alice", "Bob", "Charlie", "Dave"]
assert(names.sorted(by: \.count) == ["Bob", "Dave", "Alice", "Charlie"])
extension Collection {
subscript<T>(_ keyPath: KeyPath<Element, T>) -> [T] {
return map { $0[keyPath: keyPath] }
}
}
extension RangeReplaceableCollection {
subscript<U, T>(_ keyPath: KeyPath<Element, T>) -> U where U: RangeReplaceableCollection, U.Element == T {
return U(map { $0[keyPath: keyPath] })
}
struct AnyEquatable: Equatable {
static func ==(lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
return lhs.isEqual(rhs.value)
}
private let isEqual: (Any) -> Bool
private let value: Any
init<T: Equatable>(_ value: T) {
self.value = value
struct OrderedSet<Element: Comparable & Hashable> {
private let elements: [Element]
init<S: Sequence>(_ elements: S) where S.Element == Element {
let set = Set<Element>(elements)
let array = Array(set)
self.elements = array.sorted()
}
}
@jakebromberg
jakebromberg / Numeric+arc4random.swift
Last active November 25, 2017 22:21
Swifty wrapper around arc4random
import Foundation
public extension Numeric {
static func arc4random() -> Self {
var r: Self = 0
arc4random_buf(&r, Int(MemoryLayout<Self>.size))
return r
}
}
@jakebromberg
jakebromberg / DataStreamer.swift
Created November 19, 2017 17:24
`DataStreamer` class is a `URLSessionDataTask` delegate that logs out incoming data
extension URL {
static var WXYCStream: URL {
return URL(string: "http://audio-mp3.ibiblio.org:8000/wxyc.mp3")!
}
}
class DataStreamer: NSObject, URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
dump(data)
}