Skip to content

Instantly share code, notes, and snippets.

@estliberitas
Last active August 29, 2015 14:23
Show Gist options
  • Save estliberitas/344bab417883357b5667 to your computer and use it in GitHub Desktop.
Save estliberitas/344bab417883357b5667 to your computer and use it in GitHub Desktop.
Generate contents for Markdown file (uses Node.js)
'use strict';
// Use it like this: node gen-markdown-contents.js FILENAME
var fs = require('fs');
var lines = fs.readFileSync(process.argv[2]).toString('utf8').split(/\n\r?/);
var links = {};
var contents = lines.map(lineMapper).filter(Boolean).map(toListItem);
function getNextHash(link) {
if (!links.hasOwnProperty(link)) {
links[link] = true;
return link;
}
var i = 1;
var newLink = link + '-' + i;
while (links.hasOwnProperty(newLink)) {
newLink = link + '-' + (++i);
}
links[newLink] = true;
return newLink;
}
function lineMapper(line) {
var match = line.match(/^(#+)\s+(.*)/);
if (!match) {
return;
}
var level = match[1].length;
var title = match[2];
var text = title
.replace(/^(((`?static`?|`?const`?|void)\s)*)(`[^`]+`)?/g, '')
.replace(/`([^`]+)`/, '\'$1\'')
.trim();
if (~title.indexOf('static')) {
text = '.' + text;
}
else if (/(`[^`]+`|void)/.test(title) && !~title.indexOf('Event:')) {
text = '#' + text;
}
var hash = title
.trim()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-_]+/gi, '')
.toLowerCase();
return {
level: level,
text: text,
link: getNextHash('#' + hash)
};
}
function toListItem(itemData) {
return new Array(itemData.level + 1).join(' ') + '* [' + itemData.text + '](' + itemData.link + ')';
}
console.log(contents.join('\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment