Skip to content

Commit

Permalink
Modify the removeNewlines code to use the new enum parser
Browse files Browse the repository at this point in the history
  • Loading branch information
djbe committed May 31, 2017
1 parent e91962a commit 7b22f79
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions Sources/Filters+Strings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
import Foundation
import Stencil

enum RemoveNewlinesModes: String {
case all, leading
}

extension Filters {
enum Strings {
fileprivate static let reservedKeywords = [
Expand Down Expand Up @@ -119,23 +123,31 @@ extension Filters {
return escapeReservedKeywords(in: string)
}

/// Removes newlines and other whitespace from a string. Takes an optional Mode argument:
/// - all (default): remove all newlines and whitespaces
/// - leading: remove newlines and only leading whitespaces
///
/// - Parameters:
/// - value: the value to be processed
/// - arguments: the arguments to the function; expecting zero or one mode argument
/// - Returns: the trimmed string
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func removeNewlines(_ value: Any?, arguments: [Any?]) throws -> Any? {
let mode = arguments.first as? String ?? "all"

guard let string = value as? String else { throw Filters.Error.invalidInputType }
let mode = try Filters.parseEnum(from: arguments, default: RemoveNewlinesModes.all)

switch mode {
case "all":
case .all:
return string
.components(separatedBy: .whitespacesAndNewlines)
.joined()
case "leading":
case .leading:
return string
.components(separatedBy: .newlines)
.map { String($0.unicodeScalars.drop(while: { CharacterSet.whitespaces.contains($0) })) }
.joined()
.trimmingCharacters(in: .whitespaces)
default:
throw Filters.Error.invalidOption(option: mode)
}
}

Expand Down

0 comments on commit 7b22f79

Please sign in to comment.