Created
June 27, 2018 21:26
-
-
Save digoreis/b773ceb49dfc0f7829e4dd2021983067 to your computer and use it in GitHub Desktop.
A sample about cache LRU and used LinkedList for more performance in remove and include items.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
class Node<T,I: Hashable> { | |
let value: T | |
let index: I | |
var next: Node? | |
init(value: T,index: I) { | |
self.value = value | |
self.index = index | |
} | |
deinit { | |
print("☠️ this value \(value)") | |
} | |
} | |
struct LinkedListWithMaxSizeIterator<T,I: Hashable>: IteratorProtocol { | |
let linkedList: LinkedListWithMaxSize<T,I> | |
var lastPointer: Node<T, I>? | |
init(_ linkedList: LinkedListWithMaxSize<T,I>) { | |
self.linkedList = linkedList | |
} | |
mutating func next() -> T? { | |
guard linkedList.size > 0 else { return nil } | |
if lastPointer == nil { | |
lastPointer = linkedList.head | |
return lastPointer?.value | |
} | |
let returnValue = lastPointer?.next?.value | |
lastPointer = lastPointer?.next | |
return returnValue | |
} | |
} | |
class LinkedListWithMaxSize<T, I: Hashable> : Sequence { | |
var head: Node<T,I>? | |
var tail: Node<T,I>? | |
var size: Int = 0 | |
let maxSize: Int | |
init(maxSize: Int) { | |
self.maxSize = maxSize | |
} | |
func add(_ node: Node<T,I>) -> Node<T,I>? { | |
if tail != nil { | |
tail?.next = node | |
tail = node | |
} else { | |
head = node | |
tail = node | |
} | |
size = size + 1 | |
return verifySize() | |
} | |
func verifySize() -> Node<T,I>? { | |
guard size > maxSize else { return nil } | |
let oldHead = self.head | |
self.head = self.head?.next | |
return oldHead | |
} | |
func makeIterator() -> LinkedListWithMaxSizeIterator<T,I> { | |
return LinkedListWithMaxSizeIterator<T,I>(self) | |
} | |
} | |
class CacheLRU<T,I: Hashable> { | |
var list: LinkedListWithMaxSize<T,I> | |
var indexTable = [I : Node<T,I>]() | |
init(size: Int) { | |
self.list = LinkedListWithMaxSize<T,I>(maxSize: size) | |
} | |
func saveCache(_ value: T,at index: I) { | |
let node = Node<T,I>(value: value,index: index) | |
guard let removeNode = list.add(node) else { return } | |
indexTable.removeValue(forKey: removeNode.index) | |
indexTable[node.index] = node | |
} | |
func getValue(at index: I) -> T? { | |
return indexTable[index]?.value | |
} | |
} | |
let cache = CacheLRU<String,String>(size: 2) | |
cache.saveCache("apple", at: "a") | |
cache.saveCache("ball", at: "b") | |
cache.saveCache("car", at: "c") | |
cache.saveCache("day", at: "d") | |
cache.saveCache("earth", at: "e") | |
cache.saveCache("flower", at: "f") | |
cache.list.forEach { value in | |
print(value) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment