Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Last active January 22, 2021 22:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airspeedswift/83eee31e1d9e52fd5570 to your computer and use it in GitHub Desktop.
Save airspeedswift/83eee31e1d9e52fd5570 to your computer and use it in GitHub Desktop.
Removing duplicates
// removes all but first occurrence from a sequence, returning an array.
// requires elements to be hashable, not just equatable, but the alternative
// of using contains is very inefficient
// alternatively, could require comparable, sort, and remove adjacent dupes
func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(seq: S) -> [E] {
var seen: [S.Generator.Element:Int] = [:]
return filter(seq) { !seen.updateValue(1, forKey: $0).hasValue }
}
// TODO: a version that takes a custom comparator function, say for lexicographic deduping
// give String an initializer of a sequence of characters.
// (I'm not missing an existing one am I?)
extension String {
init<S: SequenceType where S.Generator.Element == Character>(_ seq: S) {
self.init()
self.extend(seq)
}
}
// removeDuplicates returns a version of the String with
// all duplicates removed
extension String {
func removeDuplicates() -> String {
return String(uniq(self))
}
}
let s = "hello, I must be going".removeDuplicates()
// => "helo, Imustbgin"
@lytzen
Copy link

lytzen commented Aug 12, 2014

Cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment