I have a string of type:
'??__HELLO__?? WORLD ##SAMPLE --MAIN--##'
And I need to parse it and get array that contains:
[{ marker: '??', value: { marker: '__', value: 'HELLO' }, ' WORLD ', { marker: '##', value: ['SAMPLE ' , { marker: '--', value: 'MAIN' }]]
So I have this arkers:
this.markers = {
b: '??',
i: '##',
u: '__',
s: '--',
};
And I have a function that generates stack:
parse(string) {
this.string = string;
this.stack = [];
for (let i = 0; i < string.length; i++) {
for (let marker of Object.values(this.markers)) {
if (string[i] + string[i + 1] === marker) {
this.stack.push({ marker: marker, index: i });
this.stack.push('');
i++;
break;
} else if (marker === Object.values(this.markers)[Object.values(this.markers).length - 1]) {
this.stack[this.stack.length - 1] = this.stack[this.stack.length - 1].concat(string[i]);
break;
}
}
}
for (let i = 0; i < this.stack.length; i++) {
if (this.stack[i] === '') {
this.stack.splice(i, 1);
i--;
}
}
console.log(this.stack);
return this.parseRecursively(this.stack[0]);
}
In my example stack will contain:
[ { marker: '??', index: 0 },
{ marker: '__', index: 2 },
'HELLO',
{ marker: '__', index: 9 },
{ marker: '??', index: 11 },
' WORLD ',
{ marker: '##', index: 20 },
'SAMPLE ',
{ marker: '--', index: 26 },
'MAIN',
{ marker: '--', index: 31 },
{ marker: '##', index: 33 } ]
And this function calls another one that recursively will generate the output array:
parseRecursively(element) {
if (this.stack.length === 0) {
return;
}
let parsed = [];
for (let i = this.stack.indexOf(element); i < this.stack.length; i++) {
if (typeof this.stack[i] === 'object') {
if (this.stack[i].marker === this.stack[this.stack.indexOf(this.stack[i]) + 1].marker) {
let popped = this.stack.splice(this.stack.indexOf(this.stack[i]) + 1, 1)[0];
let popped2 = this.stack.splice(this.stack.indexOf(this.stack[i]), 1)[0];
return { marker: popped.marker, value: this.string.substring(popped2.index + 2, popped.index) };
} else {
parsed.push({ marker: this.stack[i].marker, value: this.parseRecursively(this.stack[this.stack.indexOf(this.stack[i]) + 1]) });
i = -1;
}
} else {
parsed.push(this.stack.splice(this.stack.indexOf(this.stack[i]), 1)[0]);
i -= 2;
}
}
I tried many implementations of the above function but it still fails to parse the string.
So how can I rewrite this function so it would work?
Thanks!
P.S. Only plain JavaScript, nothing more and I think using regular expressions will help solve it easier, here's mine regex:
this.regex = /(\?{2}|#{2}|\-{2}|_{2})(.+?)(\1)/g;
## Something\nvs## Something ##)?function parse(str) { const regex = /(\?\?|__|##|--)(.*?)(\1)/; return regex.test(str) ? str.split(regex).filter(_ => _).map(parse).reduce((c, v) => c.concat(v), []) : str; }would that be a start?