JavaScript Highlighter: Handle ternary expressions

This commit is contained in:
Shadowfacts 2020-04-04 10:08:47 -04:00
parent 5b9f59ec09
commit a976cf894f
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
2 changed files with 21 additions and 2 deletions

View File

@ -19,6 +19,7 @@ fileprivate let identifierStarts: CharacterSet = {
return set return set
}() }()
fileprivate let operators = CharacterSet(charactersIn: "+-*/<>=") fileprivate let operators = CharacterSet(charactersIn: "+-*/<>=")
fileprivate let expressionEnds = CharacterSet(charactersIn: ",]});")
class JavaScriptHighlighter { class JavaScriptHighlighter {
private let text: String private let text: String
@ -71,7 +72,7 @@ class JavaScriptHighlighter {
], range: fullRange) ], range: fullRange)
currentIndex = text.startIndex currentIndex = text.startIndex
while currentIndex < text.endIndex { while let char = peek(), !expressionEnds.contains(char) {
consumeExpression() consumeExpression()
} }
@ -116,6 +117,8 @@ class JavaScriptHighlighter {
consumeArray() consumeArray()
} else if char == "." { } else if char == "." {
consumeDotLookup() consumeDotLookup()
} else if char == "?" {
consumeTernaryExpression()
} else { } else {
consume() consume()
} }
@ -310,6 +313,22 @@ class JavaScriptHighlighter {
} }
} }
func consumeTernaryExpression() {
consume() // ?
print("Ternary expression")
indent += " "
print("Ternary true result")
while let char = peek(), char != ":" {
consumeExpression() // true result
}
consume() // :
print("Ternary false result")
while let char = peek(), !expressionEnds.contains(char) {
consumeExpression()
}
indent = String(indent.dropLast(2))
}
} }
extension JavaScriptHighlighter { extension JavaScriptHighlighter {

View File

@ -8,6 +8,6 @@
import Foundation import Foundation
let source = "{a: 1234 , 'b': 'blah', foo}" let source = "a ? 'foo' : b ? 'bar' : 'baz'"
_ = JavaScriptHighlighter(text: source).highlight() _ = JavaScriptHighlighter(text: source).highlight()