Skip to content

Commit

Permalink
fix: Refactored section split logic (#200)
Browse files Browse the repository at this point in the history
Co-authored-by: Kevin Partington <kevin.partington@kernelpanicstudios.com>
  • Loading branch information
wraithgar and platinumazure committed Apr 12, 2023
1 parent 6a3cb38 commit ad4b5d8
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions lib/ini.js
Expand Up @@ -33,7 +33,7 @@ const encode = (obj, opt = {}) => {
}

for (const k of children) {
const nk = dotSplit(k).join('\\.')
const nk = splitSections(k, '.').join('\\.')
const section = (opt.section ? opt.section + '.' : '') + nk
const child = encode(obj[k], {
...opt,
Expand All @@ -49,13 +49,31 @@ const encode = (obj, opt = {}) => {
return out
}

const dotSplit = str =>
str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
.replace(/\\\./g, '\u0001')
.split(/\./)
.map(part =>
part.replace(/\1/g, '\\.')
.replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'))
function splitSections (str, separator) {
var lastMatchIndex = 0
var lastSeparatorIndex = 0
var nextIndex = 0
var sections = []

do {
nextIndex = str.indexOf(separator, lastMatchIndex)

if (nextIndex !== -1) {
lastMatchIndex = nextIndex + separator.length

if (nextIndex > 0 && str[nextIndex - 1] === '\\') {
continue
}

sections.push(str.slice(lastSeparatorIndex, nextIndex))
lastSeparatorIndex = nextIndex + separator.length
}
} while (nextIndex !== -1)

sections.push(str.slice(lastSeparatorIndex))

return sections
}

const decode = str => {
const out = Object.create(null)
Expand Down Expand Up @@ -126,7 +144,7 @@ const decode = str => {

// see if the parent section is also an object.
// if so, add it to that, and mark this one for deletion
const parts = dotSplit(k)
const parts = splitSections(k, '.')
p = out
const l = parts.pop()
const nl = l.replace(/\\\./g, '.')
Expand Down

0 comments on commit ad4b5d8

Please sign in to comment.