Last active
May 9, 2018 18:30
-
-
Save mgechev/7aa4bbaf050a178f313b4a653d6fdb27 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const { readFileSync, writeFileSync } = require('fs'); | |
const re = /\[.*?\](\(.*?\))/g | |
const addFootnotes = (path, output, ignoreRegExps = []) => { | |
let text = readFileSync(path).toString(); | |
let match; | |
let current = 1; | |
const matches = []; | |
const links = {}; | |
while (match = re.exec(text)) { | |
const link = match[1].substring(1, match[1].length - 1); | |
if (ignoreRegExps.reduce((a, c) => a || c.test(link), false)) { | |
continue; | |
} | |
if (links[link] === undefined) { | |
links[link] = current++; | |
} | |
matches.push({ start: match.index, str: match[0], idx: current - 1 }); | |
} | |
let linksList = []; | |
Object.keys(links).forEach(l => linksList[links[l] - 1] = l); | |
const notes = linksList.map((l, idx) => `${idx + 1}. [###] ${l}`).join('\n'); | |
for (let i = matches.length - 1; i >= 0; i--) { | |
const c = matches[i]; | |
text = text.substr(0, c.start + c.str.length) + '<sup>' + c.idx + '</sup>' + text.substr(c.start + c.str.length, text.length) | |
} | |
const result = text + '\n\n' + notes + '\n'; | |
return writeFileSync(output, result); | |
}; | |
module.exports.addFootnotes = addFootnotes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment