Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active July 14, 2020 17:24
Show Gist options
  • Save khanlou/4986e186efa458b97829584cb2dc0058 to your computer and use it in GitHub Desktop.
Save khanlou/4986e186efa458b97829584cb2dc0058 to your computer and use it in GitHub Desktop.
extension Sequence {
func smallest(_ n: Int, usingTest areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] {
var result = self.prefix(n).sorted(by: areInIncreasingOrder)
for e in self.dropFirst(n) {
if let insertionIndex = result.firstIndex(where: { areInIncreasingOrder(e, $0) }) {
result.insert(e, at: insertionIndex)
result.removeLast()
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment