Last active
November 25, 2015 20:18
-
-
Save bitwit/d8a13787922d700716d9 to your computer and use it in GitHub Desktop.
A functional javascript approach to a basic markdown parser. Inspired by a real interview question.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('underscore') | |
var lines = [ | |
"#The test", | |
"###Hello World", | |
"This is a new paragraph.", | |
"It has a second line", | |
"", | |
"This is my new paragraph" | |
]; | |
var htmlTemplate = _.template("<<%= tag %>><%= content %></<%= tag %>>"); | |
function getFirstCharacter (line) { | |
return line[0]; | |
} | |
function getHeadingLevel (line) { | |
var level = 0; | |
_.every(line, function (letter) { | |
if(_.isEqual(letter, "#")) { | |
level++; | |
return true; | |
} | |
return false; | |
}); | |
return level; | |
}; | |
function parseHeader (line) { | |
var level = getHeadingLevel(line); | |
return htmlTemplate({ | |
tag: "h" + level, | |
content: line.substring(level, line.length) | |
}); | |
}; | |
function parseNewLine (line) { | |
return "<br />"; | |
}; | |
function parseParagraph (line) { | |
return ""; | |
}; | |
function parse (line) { | |
switch (getFirstCharacter(line)) { | |
case '#': | |
return parseHeader(line); | |
case undefined: | |
return parseNewLine(line); | |
default: | |
return parseParagraph(line); | |
} | |
} | |
function appendLineToBuffer (line, buffer) { | |
if(_.isEmpty(buffer)) { | |
return line; | |
} | |
return buffer + ' ' + line; | |
} | |
function addOutstandingBufferToOutput (buffer, output) { | |
if(!_.isEmpty(buffer)) { | |
var newOutput = _.clone(output); | |
newOutput.push(htmlTemplate({ | |
tag: "p", | |
content: buffer | |
})); | |
return newOutput; | |
} else { | |
return output; | |
} | |
} | |
function parseMarkdown (lines) { | |
var buffer = ""; | |
var result = _.reduce(lines, function (output, line) { | |
var newData = parse(line); | |
if(!_.isEmpty(newData)) { | |
var newOutput = addOutstandingBufferToOutput(buffer, output); | |
buffer = ""; | |
newOutput.push(newData); | |
return newOutput; | |
} else { | |
buffer = appendLineToBuffer(line, buffer); | |
return output; | |
} | |
}, []); | |
return addOutstandingBufferToOutput(buffer, result).join("\n"); | |
} | |
console.log(parseMarkdown(lines)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment