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
}()
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 {

View File

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