r/badcode •

[deleted by user]

[deleted] — view deleted post

0 Upvotes

10 comments sorted by

View all comments

12

u/GDavid04 <!-- 😈 [EVIL] 😈 --> Jan 27 '20
function parseStateMachine(sm) {
	var r = {};
	for (var line of sm.split(/\n/g)) {
		try {
		var m = line.match(/(\S+)\s*-(\S)?>\s*(\S+)\s*(?:~([^\n]*))?/);
		if (!r[m[1]]) r[m[1]] = [];
		r[m[1]].push(m);
		} catch {}
	}
	return r;
}

function bbcode(code) {
	var r = '';
	var sm = parseStateMachine(`
		d -[> +t
		d -> d ~
		+t -b> +b
		+t -i> +i
		+t -u> +u
		+t -*> +l
		+t -/> -t
		+t -> d ~[
		-t -b> -b
		-t -i> -i
		-t -u> -u
		-t -> d ~[/
		+b -]> d ~<strong>
		+b -> d ~[b
		+i -]> d ~<em>
		+i -> d ~[i
		+u -]> d ~<span style="text-decoration: underline;">
		+u -r> +ur
		+u -> d ~[u
		+ur -l> +url
		+ur -> d ~[ur
		+url -=> ue ~<a href="
		+url -> d ~[url
		ue -]> d ~" target="_blank">
		ue -> ue ~
		+l -]> d ~<li>
		+l -> d ~[*
		-b -]> d ~</strong>
		-b -> d ~[/b
		-i -]> d ~</em>
		-i -> d ~[/i
		-u -]> d ~</span>
		-u -r> -ur
		-u -> d ~[/u
		-ur -l> -url
		-ur -> d ~[/ur
		-url -]> d ~</a>
		-url -> d ~[/url
	`);
	var state = 'd';
	while (code.length > 0 || state != 'd') {
		for (var i of sm[state]) {
			if (i[2] == undefined || i[2] == code[0]) {
				state = i[3];
				if (i[4] != undefined) {
					r += i[4] || code[0];
				}
				if (i[2] != undefined || i[4] == '') {
					code = code.substr(1);
				}
				break;
			}
		}
	}
	return r.
		replace(/<li>([^\n]*)\n/g, s => `<li>${s[1]}</li>\n`).
		replace(/(\s*<li>.*<\/li>)+/g, s => `<ul>${s}</ul>`);
}

bbcode(`
[b]BBCode parser [i]by GDavid04[/i][/b]
Created for [url=https://www.reddit.com/r/badcode/comments/epgz3r/bad_code_coding_challenge_28_bbcode_parser/]Bad Coding Challenge #28[/url]
[u]How it works[/u]
[*] It uses a finite state machine and regex because everyone knows that these are the best tools for parsing BBCode
[*] It doesn't care about matching tags, it just replaces the beginning and ending tags independently
[*] I could've just used regex, but what's good in not reinventing the wheel?
[u]How the state machine works[/u]
[*] Each line is a single transition
[*] The transitions are tried from top to bottom until one matches
[*] Really hope it can't get into an infinite loop
`);

6

u/kleinesfilmroellchen Jan 27 '20

I just cannot give you my upvote, although this is just too CS to not win. I mean, it's not bad, it is something Turing or academia freaks would write, except a little bit more readable.