JavaScript Highlighter: Handle ternary expressions
This commit is contained in:
parent
5b9f59ec09
commit
a976cf894f
|
@ -19,6 +19,7 @@ fileprivate let identifierStarts: CharacterSet = {
|
|||
return set
|
||||
}()
|
||||
fileprivate let operators = CharacterSet(charactersIn: "+-*/<>=")
|
||||
fileprivate let expressionEnds = CharacterSet(charactersIn: ",]});")
|
||||
|
||||
class JavaScriptHighlighter {
|
||||
private let text: String
|
||||
|
@ -71,7 +72,7 @@ class JavaScriptHighlighter {
|
|||
], range: fullRange)
|
||||
|
||||
currentIndex = text.startIndex
|
||||
while currentIndex < text.endIndex {
|
||||
while let char = peek(), !expressionEnds.contains(char) {
|
||||
consumeExpression()
|
||||
}
|
||||
|
||||
|
@ -116,6 +117,8 @@ class JavaScriptHighlighter {
|
|||
consumeArray()
|
||||
} else if char == "." {
|
||||
consumeDotLookup()
|
||||
} else if char == "?" {
|
||||
consumeTernaryExpression()
|
||||
} else {
|
||||
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 {
|
||||
|
|
|
@ -8,6 +8,6 @@
|
|||
|
||||
import Foundation
|
||||
|
||||
let source = "{a: 1234 , 'b': 'blah', foo}"
|
||||
let source = "a ? 'foo' : b ? 'bar' : 'baz'"
|
||||
_ = JavaScriptHighlighter(text: source).highlight()
|
||||
|
||||
|
|
Loading…
Reference in New Issue