I was looking at Markdown parsers written in JS, and found marked. Ever curious about how different people tackle parsers, I was completely blown away by the elegance of its code. One function in particular stood out:


It’s basically just a shortcut to String.prototype.replace, but the syntax that it enables is beautiful:


Looking through the source history, at one point it was literally just sequential calls to String.prototype.replace:


I think it’s very interesting to study how code evolves over time.

As an experiment, I applied that replace function to the regex I wrote for MiniVash. For a one-shot use like this, breaking the regex up is not worth the size increase. However the comprehension and readability improve immensely:

var re = {};

re.identifier = /[a-zA-Z]+?[a-zA-Z0-9]/
re.inExp = /[a-zA-Z0-9'".()=?:]/
re.pAccess = /(?:[.]+(?!\s|$|"|'|\?))/

re.exp = /(?:identifier*(?:pAccess|(?:\[inExp+\])|(?:\(inExp*\)))*)/
re.keyword = /do|for|function|(?:exp+\(\s*function)|if|switch|try|while|with/

re.combined = /(@(?!keyword)(?:exp+))|(@\(?:.*?\)@)/
re.combined = replace( re.combined, 'g' )
	(/keyword/g, re.keyword)
	(/exp/g, re.exp)
	(/identifier/g, re.identifier)
	(/pAccess/g, re.pAccess)
	(/inExp/g, re.inExp)