First attempt at Python port, expand tests.
This commit is contained in:
35
packages/python/parser.py
Normal file
35
packages/python/parser.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from typing import TypedDict
|
||||
|
||||
class LineData(TypedDict):
|
||||
line: str
|
||||
indent: str
|
||||
level: int
|
||||
offsetHead: int
|
||||
offsetTail: int
|
||||
|
||||
def createLineData(line: str = '', indent: str = ' ') -> LineData:
|
||||
return { "line": line, "indent": indent, "level": 0, "offsetHead": 0, "offsetTail": 0 }
|
||||
|
||||
def parseLine(lineData: LineData) -> LineData:
|
||||
# if ((typeof lineData !== 'object' || !lineData) || typeof lineData.level !== 'number') throw new Error(`'lineData' must be an object with string line and numeric level properties`)
|
||||
# if (typeof lineData.indent !== 'string' || lineData.indent.length === 0 || lineData.indent.length > 1) throw new Error(`'lineData.indent' must be a single-character string`)
|
||||
# if (typeof lineData.line !== 'string') throw new Error(`'lineData.line' must be a string`)
|
||||
|
||||
level = 0
|
||||
|
||||
# Repeat previous level for blank lines.
|
||||
if len(lineData['line']) == 0:
|
||||
lineData['level'] = lineData['level']
|
||||
lineData['offsetHead'] = 0
|
||||
lineData['offsetTail'] = 0
|
||||
else:
|
||||
while level < len(lineData['line']) and lineData['line'][level] == lineData['indent'] and level <= lineData['level'] + 1:
|
||||
level += 1
|
||||
lineData['level'] = level
|
||||
lineData['offsetHead'] = level
|
||||
lineData['offsetTail'] = level
|
||||
|
||||
while lineData['offsetTail'] < len(lineData['line']) and lineData['line'][lineData['offsetTail']] != ' ':
|
||||
lineData['offsetTail'] += 1
|
||||
|
||||
return lineData
|
||||
Reference in New Issue
Block a user