Skip to content

Instantly share code, notes, and snippets.

View loromits's full-sized avatar

Anton Kovtun loromits

  • Mykolayiv, Ukraine
View GitHub Profile
@loromits
loromits / DictionaryKeyPathSet.swift
Created October 30, 2019 09:19
Change value in nested json dictionary
extension Dictionary where Key == String, Value == Any {
@dynamicMemberLookup
struct LookupPath {
fileprivate let path: [String]
subscript(dynamicMember member: String) -> LookupPath {
LookupPath(path: path + [member])
}
}
@loromits
loromits / JSONContainer.swift
Created October 2, 2019 08:21
Dynamic member lookup based simplification to access nested dictionary fields
@dynamicMemberLookup
final class JSONContainer {
private typealias Dict = [String: Any]
private enum Container {
case dict(Dict), value(Any), nothing
}
private let _container: Container
init(_ dict: [String: Any]) {
@loromits
loromits / ColorInterpolation.swift
Created September 4, 2019 09:15
Create gradient color interpolation of 2 UIColors
import UIKit
extension Comparable {
func clamping(_ range: ClosedRange<Self>) -> Self {
return Swift.min(range.upperBound, max(range.lowerBound, self))
}
}
extension UIColor {
func components() -> (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
extension Array {
/// Union with newElements, comparing by keyPath value and replacing old elements with new
/// Expected complexity ~ 3*n
func union<T: Hashable>(newElements: Array, byKeyPath keyPath: KeyPath<Element, T>) -> Array {
var copy = self
// Hash indices for faster replacement
let sample = copy.enumerated().reduce(into: [T: Index]()) { result, entry in
result[entry.element[keyPath: keyPath]] = entry.offset
}
copy.reserveCapacity(copy.count + newElements.count)
import RxSwift
struct MaybeNever<S: AnyObject> {
private weak var take: S?
init(_ t: S) {
take = t
}
func run<A, B, R>(_ f: @escaping (S, A, B) -> Observable<R>) -> (A, B) -> Observable<R> {
return { a, b in
if let t = self.take {
import Network
extension NWPathMonitor: ReactiveCompatible {}
extension Reactive where Base == NWPathMonitor {
func pathUpdate(on queue: DispatchQueue = .global(qos: .background)) -> Observable<NWPath> {
return Observable.create { [weak base] observer in
base?.pathUpdateHandler = observer.onNext
base?.start(queue: queue)
return Disposables.create { base?.cancel() }
@loromits
loromits / TrailingZerosCounter.cpp
Last active November 3, 2018 00:55
Counts trailing zeroes in `n!` represented in `k`-based numeric system
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
std::vector<bool> sieve() {
std::vector<bool> v(5001, true);
v[0] = v[1] = false;
for (int p = 2; p < 5001; p++) {
if (v[p]) {
@loromits
loromits / Combinations.cpp
Created October 12, 2018 19:46
Outputs all non-empty combinations for given number. `assert(n > 0)`
#include <iostream>
#include <vector>
#include <numeric>
bool lift(std::vector<int>& vec, int limit) {
if (vec.back() < limit) {
vec.back() += 1;
return true;
}
for (auto rit = std::next(vec.rbegin()); rit != vec.rend(); rit++) {
@loromits
loromits / Pair.m
Created September 14, 2018 10:00
Simple stupid Pair in Objective-C
@interface Pair<FirstType, SecondType>: NSObject
@property FirstType first;
@property SecondType second;
+ (instancetype)pairWithFirst:(FirstType)first second:(SecondType)second;
@end
@implementation Pair
@loromits
loromits / 3SUM.swift
Last active September 4, 2018 08:49
3SUM problem raw algorithm with O(n²) at worst
extension Collection where Element: Comparable & Numeric {
typealias Triplet = (Element, Element, Element)
func threeSum() -> [Triplet] {
var result = [Triplet]()
let sortedSelf = sorted()
for (offset, a) in sortedSelf.dropLast().enumerated() {
var slice = sortedSelf.dropFirst(offset + 1)
while slice.count > 1, let b = slice.first, let c = slice.last {
if a + b + c == 0 {