Last active
October 5, 2016 09:30
-
-
Save estliberitas/8ed9d42c0c938a86c88e6d3a5f42e37a to your computer and use it in GitHub Desktop.
Generate table of contents for markdown file
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
'use strict'; | |
const fs = require('fs'); | |
const readline = require('readline'); | |
const filename = process.argv[2]; | |
const stream = fs.createReadStream(filename); | |
const rl = readline.createInterface({input: stream}); | |
let currentLevel = 0; | |
const linkRevisions = {}; | |
rl.on('line', (line) => { | |
// Skip top header | |
if (line.indexOf('##') !== 0) { | |
return; | |
} | |
const match = line.match(/^(#+)\s+([^$]+)\n?$/); | |
const offset = ' '.repeat(match[1].length - 2); | |
const label = match[2]; | |
const link = label | |
.toLowerCase() | |
.replace(/[^a-z0-9\s]/g, '') | |
.replace(/[\s]+/g, '-'); | |
// Every duplicate of some link will have hash with appended dash and | |
// duplicate number. I.e. if some section has #link hash, its duplicates will | |
// have hashes #link-1, link-2 and so on. | |
let linkWithRevision = link; | |
if (!linkRevisions[link]) { | |
linkRevisions[link] = 1; | |
} | |
else { | |
linkWithRevision = link + '-' + linkRevisions[link]; | |
++linkRevisions[link]; | |
} | |
console.log(`${offset}- [${label}](#${linkWithRevision})`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment