Skip to content

Instantly share code, notes, and snippets.

@regnerjr
Created March 27, 2015 00:52
Show Gist options
  • Select an option

  • Save regnerjr/1ecfdd30c6ff928a402d to your computer and use it in GitHub Desktop.

Select an option

Save regnerjr/1ecfdd30c6ff928a402d to your computer and use it in GitHub Desktop.
A simple rewriting of the uniq command line tool.
#!/usr/bin/env xcrun swift -F $(xcode-select)/Platforms/MacOSX.platform/Developer/Library/Frameworks
import Foundation
//need to process any arguements here
//
// uniq [-c | -d | -u] [-i] [-f num] [-s chars] [input_file [output_file]]
// MARK: Standard In , Standard Out
func getStandardInput() -> String? {
let standardInput = NSFileHandle.fileHandleWithStandardInput()
let input = standardInput.availableData
return NSString(data: input, encoding: NSASCIIStringEncoding) as String?
}
func writeStandardOutput(out: String){
let standardOutput = NSFileHandle.fileHandleWithStandardOutput()
if let data = out.dataUsingEncoding(NSASCIIStringEncoding){
standardOutput.writeData(data)
}
}
// MARK: Start Script
let input = getStandardInput()
if input == nil {
exit(1)
}
//unwrap this since we know input is not nil
var separated = input?.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
separated?.removeLast()
func _uniq<T: Equatable>(initial: [T], next: T) -> [T]{
if initial.last! != next {
return initial + [next]
} else {
return initial
}
}
func uniq<T: Equatable>(a: Array<T>) -> Array<T>{
let tooSmallToSort = a.count < 2
switch tooSmallToSort {
case true: return a
case false: return a.reduce([a.first!], combine: _uniq)
default: println("Bool is not true or false. I am going crazy")
return []
}
}
if let separated = separated{
let results = uniq(separated)
writeStandardOutput( results.reduce("", { $0 + $1 + "\n"}) )
} else {
exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment