Created
June 11, 2020 23:14
-
-
Save coreyd303/74688aad492cad46dd83c9da1f450110 to your computer and use it in GitHub Desktop.
This code complements https://diningwithrobots.com/2020/06/11/rna-transcription-in-swift/
This file contains 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
struct Nucleotide { | |
private let validNucleotides = "ATCG" | |
private var errorMessage: ((Character) -> (String)) = { n in | |
return "\(n) is not a valid Nucleotide" | |
} | |
let dna: String | |
init(_ dna: String) { | |
self.dna = dna | |
} | |
} | |
extension Nucleotide { | |
func complementOfDNA() throws -> String { | |
var sequence: String = "" | |
try dna.forEach { n in | |
if !validNucleotides.contains(n) { | |
throw TranscriptionError.invalidNucleotide("\(n) is not a valid Nucleotide") | |
} | |
if n == "G" { | |
sequence += "C" | |
} else if n == "C" { | |
sequence += "G" | |
} else if n == "T" { | |
sequence += "A" | |
} else if n == "A" { | |
sequence += "U" | |
} | |
} | |
return sequence | |
} | |
} | |
// Refactor to switch and improve error handling | |
extension Nucleotide { | |
func complementOfDNA() throws -> String { | |
var sequence: String = "" | |
try dna.forEach { n in | |
switch n { | |
case "G": | |
sequence += "C" | |
case "C": | |
sequence += "G" | |
case "T": | |
sequence += "A" | |
case "A": | |
sequence += "U" | |
default: | |
throw TranscriptionError.invalidNucleotide(errorMessage(n)) | |
} | |
} | |
return sequence | |
} | |
} | |
// using map to reduce code | |
extension Nucleotide { | |
func complementOfDNA() throws -> String { | |
return try dna.map { (n) -> String in | |
switch String(n) { | |
case "G": return "C" | |
case "C": return "G" | |
case "T": return "A" | |
case "A": return "U" | |
default: | |
throw TranscriptionError.invalidNucleotide(errorMessage(n)) | |
} | |
}.joined() | |
} | |
} | |
// with map and enum | |
extension Nucleotide { | |
func complementOfDNA() throws -> String { | |
return try dna.map { (n) -> String in | |
if let t = nucleotide(rawValue: n)?.transcribe() { | |
return t | |
} else { | |
throw TranscriptionError.invalidNucleotide(errorMessage(n)) | |
} | |
}.joined() | |
} | |
} | |
extension Nucleotide { | |
private enum nucleotide: Character { | |
case A = "A" | |
case T = "T" | |
case G = "G" | |
case C = "C" | |
func transcribe() -> String? { | |
switch self { | |
case .A: return "U" | |
case .T: return "A" | |
case .G: return "C" | |
case .C: return "G" | |
} | |
} | |
} | |
} | |
enum TranscriptionError: LocalizedError { | |
case invalidNucleotide(_ n: String) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment