Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
jakebromberg / AVAssetTrim.swift
Last active October 4, 2023 23:57 — forked from acj/TrimVideo.swift
Trim video using AVFoundation in Swift
import AVFoundation
import Foundation
extension FileManager {
func removeFileIfNecessary(at url: URL) throws {
guard fileExists(atPath: url.path) else {
return
}
do {
@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] }
}
}
@propertyWrapper
struct CopyOnWrite<Object> {
var wrappedValue: Object {
get { storage.object }
set {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.copy()
}
storage.object = newValue
}
struct Matrix<Element> {
private var storage: [[Element]]
init(_ storage: [[Element]]) {
self.storage = storage
}
}
extension Matrix: Collection {
struct Index: Comparable {
final class Node<Value>: Sequence {
typealias NextNode = Node<Value>?
let value: Value
var next: NextNode
init(value: Value, nextNode: NextNode = nil) {
self.value = value
self.next = nextNode
}
import Foundation
final class Threadsafe<Value> {
init(_ value: Value) {
self._value = value
}
var value: Value {
return queue.sync { return _value }
}
final class Node<T>: Sequence {
let value: T
var next: Node<T>?
init(_ value: T, next: Node<T>?) {
self.value = value
self.next = next
}
func makeIterator() -> List<T> {
extension Sequence where Element == Int {
func pairsOfSum(k: Int) -> [(Int, Int)] {
var cache = [Int:Int]()
var result = [(Int, Int)]()
for i in self {
cache[i] = k - i
}
for (num, inv) in cache {
@jakebromberg
jakebromberg / AlmostIncreasingSequence.swift
Last active January 9, 2019 17:53 — forked from jakehawken/AlmostIncreasingSequence.swift
For the "almostIncreasingSequence" problem on CodeFights:
extension Sequence where Element: Comparable {
func isAlmostIncreasingSequence() -> Bool {
var foundMisplacedElement = false
for (a, b) in zip(self, self.dropFirst()) where a >= b {
guard !foundMisplacedElement else { return false }
foundMisplacedElement = true
}
@jakebromberg
jakebromberg / ThreadSafe.h
Last active August 24, 2018 18:54
Inspired by Chris Lattner's concurrency manifesto, this defines a generic thread-safe object in Objective-C, similar to how Chris describes the behavior of actors.
@import Foundation;
@interface ThreadSafe<Value>: NSProxy
- (instancetype)initWithValue:(Value)value;
@property (nonatomic, strong, readonly) Value value;
@end