Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Even faster array parsing #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 13 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ const NULL_STRING = 'NULL'
function makeParseArrayWithTransform (transform) {
const haveTransform = transform != null
return function parseArray (str) {
const rbraceIndex = str.length - 1
if (rbraceIndex === 1) {
return []
}
if (str[rbraceIndex] !== RBRACE) {
throw new Error('Invalid array text - must end with }')
}

// If starts with `[`, it is specifying the index boundas. Skip past first `=`.
let position = 0
if (str[position] === LBRACKET) {
Expand All @@ -29,17 +37,12 @@ function makeParseArrayWithTransform (transform) {
if (str[position++] !== LBRACE) {
throw new Error('Invalid array text - must start with {')
}
const rbraceIndex = str.length - 1
if (str[rbraceIndex] !== RBRACE) {
throw new Error('Invalid array text - must end with }')
}
const output = []
let current = output
const stack = []

let currentStringStart = position
const currentStringParts = []
let hasStringParts = false
let currentString = ''
let expectValue = true

for (; position < rbraceIndex; ++position) {
Expand All @@ -56,8 +59,7 @@ function makeParseArrayWithTransform (transform) {
while (backSlash !== -1 && backSlash < dquot) {
position = backSlash
const part = str.slice(currentStringStart, position)
currentStringParts.push(part)
hasStringParts = true
currentString += part
currentStringStart = ++position
if (dquot === position++) {
// This was an escaped doublequote; find the next one!
Expand All @@ -68,14 +70,9 @@ function makeParseArrayWithTransform (transform) {
}
position = dquot
const part = str.slice(currentStringStart, position)
if (hasStringParts) {
const final = currentStringParts.join('') + part
current.push(haveTransform ? transform(final) : final)
currentStringParts.length = 0
hasStringParts = false
} else {
current.push(haveTransform ? transform(part) : part)
}
currentString += part
current.push(haveTransform ? transform(currentString) : currentString)
currentString = ''
expectValue = false
} else if (char === LBRACE) {
const newArray = []
Expand Down