Skip to content

Instantly share code, notes, and snippets.

View chriswebb09's full-sized avatar

Christopher Webb chriswebb09

View GitHub Profile
extension String {
func isValidEmail() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluate(with: self)
return result
}
}
extension Collection where Iterator.Element: Comparable {
static func mergeSort(_ items: [Iterator.Element]) -> [Iterator.Element] {
guard items.count > 1 else { return items }
let middleIndex = items.count / 2
let left = mergeSort(Array(items.reversed().suffix(middleIndex)).reversed().map { $0 })
let right = mergeSort(Array(items.suffix(from: middleIndex)))
return merge(left: left, right: right)
}
extension Array {
mutating func swapItems(itemAtIndex firstIndex: Index, withItemAtIndex secondIndex: Index) {
if firstIndex != secondIndex {
swap(&self[firstIndex], &self[secondIndex])
}
}
}
extension Sequence where Iterator.Element: Comparable {
struct HashTable<Key: Hashable, Value> {
typealias Bucket = [HashElement<Key, Value>]
var buckets: [Bucket]
init(capacity: Int) {
assert(capacity > 0)
buckets = Array<Bucket>(repeatElement([], count: capacity))
}
struct HashTable<Key: Hashable, Value> {
// Code added earlier
@discardableResult
mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
var itemIndex: Int
itemIndex = self.index(for: key)
for (i, element) in buckets[itemIndex].enumerated() {
if element.key == key {
struct HashTable<Key: Hashable, Value> {
// Prior Hash Table Implementation
func model(with element: Key) -> String? {
switch element {
case is String:
return String(describing: element)
case is Int:
let stringElement = String(describing: element)
struct HashTable<Key: Hashable, Value> {
typealias Bucket = [HashElement<Key, Value>]
var buckets: [Bucket]
init(capacity: Int) {
assert(capacity > 0)
buckets = Array<Bucket>(repeatElement([], count: capacity))
}
class Test {
var hello: [String: Int] = [:]
func test() {
hello[“one”] = 1
hello[“one”] // 1
}
}
class Node<T: Equatable> {
var value: T
weak var parent: Node<T>?
var children: [Node<T>] = []
init(value: T) {
self.value = value
}
func add(child: Node<T>) {
class Element: Hashable {
var value: Int
var hashValue: Int {
return value * 10
}
init(value: Int) {
self.value = value