Skip to content

Commit ad4b5d8

Browse files
fix: Refactored section split logic (#200)
Co-authored-by: Kevin Partington <[email protected]>
1 parent 6a3cb38 commit ad4b5d8

File tree

1 file changed

+27
-9
lines changed

1 file changed

+27
-9
lines changed

lib/ini.js

+27-9
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ const encode = (obj, opt = {}) => {
3333
}
3434

3535
for (const k of children) {
36-
const nk = dotSplit(k).join('\\.')
36+
const nk = splitSections(k, '.').join('\\.')
3737
const section = (opt.section ? opt.section + '.' : '') + nk
3838
const child = encode(obj[k], {
3939
...opt,
@@ -49,13 +49,31 @@ const encode = (obj, opt = {}) => {
4949
return out
5050
}
5151

52-
const dotSplit = str =>
53-
str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
54-
.replace(/\\\./g, '\u0001')
55-
.split(/\./)
56-
.map(part =>
57-
part.replace(/\1/g, '\\.')
58-
.replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'))
52+
function splitSections (str, separator) {
53+
var lastMatchIndex = 0
54+
var lastSeparatorIndex = 0
55+
var nextIndex = 0
56+
var sections = []
57+
58+
do {
59+
nextIndex = str.indexOf(separator, lastMatchIndex)
60+
61+
if (nextIndex !== -1) {
62+
lastMatchIndex = nextIndex + separator.length
63+
64+
if (nextIndex > 0 && str[nextIndex - 1] === '\\') {
65+
continue
66+
}
67+
68+
sections.push(str.slice(lastSeparatorIndex, nextIndex))
69+
lastSeparatorIndex = nextIndex + separator.length
70+
}
71+
} while (nextIndex !== -1)
72+
73+
sections.push(str.slice(lastSeparatorIndex))
74+
75+
return sections
76+
}
5977

6078
const decode = str => {
6179
const out = Object.create(null)
@@ -126,7 +144,7 @@ const decode = str => {
126144

127145
// see if the parent section is also an object.
128146
// if so, add it to that, and mark this one for deletion
129-
const parts = dotSplit(k)
147+
const parts = splitSections(k, '.')
130148
p = out
131149
const l = parts.pop()
132150
const nl = l.replace(/\\\./g, '.')

0 commit comments

Comments
 (0)