Sha256: a92153362bb7f58af6352d5e64876d38dc4ed85a03d29943b9b2130a6c39d43e

Contents?: true

Size: 1.96 KB

Versions: 266

Compression:

Stored size: 1.96 KB

Contents

import Foundation

private extension String {
    func substringFromIndexInt(_ indx: Int) -> String {
        let index = self.characters.index(self.startIndex, offsetBy: indx)
        return self.substring(from: index)
    }

    func substringWithRangeInt(_ intRange: Range<Int>) -> String {
        let start = self.characters.index(self.startIndex, offsetBy: intRange.lowerBound)
        let end = self.characters.index(self.startIndex, offsetBy: intRange.upperBound)
        return self.substring(with: start..<end)
    }
}

struct PigLatin {

    static func translate (_ word: String) -> String {
        return word.components(separatedBy: " ").map { self.translateWord($0) }.joined(separator: " ")
    }

    static func translateWord(_ word: String) -> String {

        func wordStartsWithPrefixes(_ word: String, prefixes: [String]) -> Bool {
            return 0 < prefixes.filter { word.hasPrefix($0) }.count
        }

        func wordStartsWithVowelLike(_ word: String) -> Bool {
            return wordStartsWithPrefixes(word, prefixes: ["xr", "yt", "a", "e", "i", "o", "u" ])
        }

        func wordStartsWithConsonantAndQu(_ word: String) -> Bool {
            let index = word.characters.index(word.startIndex, offsetBy: 1)
            return word.substring(from: index).hasPrefix("qu")
        }

        if wordStartsWithVowelLike(word) { return word + "ay" }
        if wordStartsWithPrefixes(word, prefixes: ["thr", "sch"]) {
            return (word.substringFromIndexInt(3) + word.substringWithRangeInt(0..<3) + "ay") }

        if wordStartsWithPrefixes(word, prefixes: ["ch", "qu", "th"]) {
            return word.substringFromIndexInt(2) +
                word.substringWithRangeInt(0..<2) + "ay" }
        if wordStartsWithConsonantAndQu(word) {
            return word.substringFromIndexInt(3) +
                word.substringWithRangeInt(0..<1) + "quay"}

        return word.substringFromIndexInt(1) +
            word.substringWithRangeInt(0..<1) + "ay"

    }

}

Version data entries

266 entries across 266 versions & 1 rubygems

Version Path
trackler-2.0.8.36 tracks/swift/exercises/pig-latin/Sources/PigLatinExample.swift
trackler-2.0.8.35 tracks/swift/exercises/pig-latin/Sources/PigLatinExample.swift
trackler-2.0.8.34 tracks/swift/exercises/pig-latin/Sources/PigLatinExample.swift
trackler-2.0.8.33 tracks/swift/exercises/pig-latin/Sources/PigLatinExample.swift
trackler-2.0.8.32 tracks/swift/exercises/pig-latin/Sources/PigLatinExample.swift
trackler-2.0.8.31 tracks/swift/exercises/pig-latin/Sources/PigLatinExample.swift