@@ -14,11 +14,32 @@ public class Parser {
1414 /// - parameter string: The string to parse
1515 /// - returns: An expression that will result in the value
1616 public static func parse( string: String ) -> Expression ? {
17- let updatedString = Parser . changeMinusIntoOther ( change: Operators . subOp, into: string)
17+ var updatedString = Parser . changeMinusIntoOther ( change: Operators . subOp, into: string)
1818 guard updatedString. contains ( Operators . divOp) || updatedString. contains ( Operators . multOp) || updatedString. contains ( Operators . addOp) || updatedString. contains ( Operators . subOp) || updatedString. contains ( Operators . powOp) || Decimal ( string) != nil else {
1919 return nil
2020 }
21- if updatedString. contains ( Operators . addOp) || updatedString. contains ( Operators . subOp) {
21+ if updatedString. contains ( " ( " ) {
22+ let idx = updatedString. firstIndex ( of: " ( " ) !
23+ var parenCounts = 0
24+ var nextIdx = updatedString. index ( after: idx)
25+ while nextIdx != updatedString. endIndex {
26+ if updatedString [ nextIdx] == " ) " {
27+ parenCounts -= 1
28+ } else if updatedString [ nextIdx] == " ( " {
29+ parenCounts += 1
30+ }
31+ if parenCounts == - 1 {
32+ updatedString. replaceSubrange ( idx..< nextIdx, with: " \( decimal: Parser . parse ( string: String ( updatedString [ updatedString. index ( after: idx) ..< nextIdx] ) ) ? . evaluate ( ) ) " )
33+ break
34+ }
35+ nextIdx = updatedString. index ( after: nextIdx)
36+ }
37+ if updatedString. contains ( " ( " ) {
38+ return nil
39+ } else {
40+ return Parser . parse ( string: updatedString)
41+ }
42+ } else if updatedString. contains ( Operators . addOp) || updatedString. contains ( Operators . subOp) {
2243 let addAll = updatedString. split ( separator: Operators . addOp [ Operators . addOp. startIndex] ) . map ( String . init)
2344 let subMids = addAll. map ( { string in string. split ( separator: Operators . subOp. first!) . map ( String . init) } )
2445 return subMids. reduce ( Decimal ( 0 ) as Expression , { ( result: Expression ? , next: [ String ] ) -> Expression ? in
@@ -122,3 +143,13 @@ extension Decimal: Expression {
122143 }
123144 }
124145}
146+
147+ extension String . StringInterpolation {
148+ mutating func appendInterpolation( decimal: Decimal ? ) {
149+ if let d = decimal {
150+ self . appendInterpolation ( d)
151+ } else {
152+ self . appendInterpolation ( " nil " )
153+ }
154+ }
155+ }
0 commit comments