mirror of
https://git.stupid.fish/teidesu/scripts.git
synced 2025-07-28 02:32:11 +10:00
chore: update public repo
This commit is contained in:
parent
9891d7734d
commit
2423324540
8 changed files with 531 additions and 0 deletions
54
utils/strings.ts
Normal file
54
utils/strings.ts
Normal file
|
@ -0,0 +1,54 @@
|
|||
export function parseJsObject(str: string, offset = 0) {
|
||||
let i = offset
|
||||
const len = str.length
|
||||
let start = -1
|
||||
let end = -1
|
||||
|
||||
const depth = {
|
||||
'{': 0,
|
||||
'[': 0,
|
||||
}
|
||||
|
||||
const possibleQuotes = {
|
||||
'"': true,
|
||||
'\'': true,
|
||||
'`': true,
|
||||
}
|
||||
let inQuote: string | null = null
|
||||
let escapeNextQuote = false
|
||||
|
||||
while (i < len) {
|
||||
const char = str[i]
|
||||
if (char in possibleQuotes && !escapeNextQuote) {
|
||||
if (inQuote === null) {
|
||||
inQuote = char
|
||||
} else if (char === inQuote) {
|
||||
inQuote = null
|
||||
}
|
||||
} else if (inQuote != null) {
|
||||
escapeNextQuote = char === '\\' && !escapeNextQuote
|
||||
} else if (inQuote == null && char in depth) {
|
||||
if (start === -1) {
|
||||
start = i
|
||||
}
|
||||
depth[char] += 1
|
||||
} else if (inQuote == null && (
|
||||
char === '}' || char === ']'
|
||||
)) {
|
||||
if (char === '}') depth['{'] -= 1
|
||||
if (char === ']') depth['['] -= 1
|
||||
|
||||
if (depth['{'] === 0 && depth['['] === 0) {
|
||||
end = i + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
|
||||
if (start === -1 && end === -1) return null
|
||||
if (depth['{'] !== 0 || depth['['] !== 0) throw new SyntaxError('Mismatched brackets')
|
||||
if (inQuote) throw new SyntaxError('Unclosed string')
|
||||
|
||||
return str.substring(start, end)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue