Created
February 9, 2018 05:48
-
-
Save dulao5/ce54a1d276dd9b6f5cf460efbc315c5c to your computer and use it in GitHub Desktop.
conf_page_links_to_markdown.js
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
function get_li_elts(ul) { | |
var li_elts = Array.prototype.reduce.call(ul.children, function(acc, e) { | |
if (e.tagName == 'LI') | |
acc.push(e); | |
return acc; | |
}, []); | |
console.log(li_elts); | |
var li_infos = []; | |
li_elts.forEach(function(elt){ | |
li_infos.push(get_li_info(elt)); | |
}); | |
return li_infos; | |
} | |
function get_li_info(li) { | |
var info = {}; | |
var a_elt = Array.prototype.find.call(li.children, function(elt) { | |
return elt.tagName == 'A'; | |
}); | |
console.log(a_elt); | |
if (a_elt) { | |
info.title = a_elt.textContent; | |
info.link = a_elt.href; | |
} | |
console.log(info); | |
var children_ul = Array.prototype.find.call(li.children, function(elt) { | |
return elt.tagName == 'UL' | |
}); | |
console.log(children_ul); | |
info.children = []; | |
if (children_ul) { | |
info.children = get_li_elts(children_ul); | |
} | |
console.log(info.children); | |
return info; | |
} | |
function to_markdown(tree, deep = 0) { | |
var deep = 0; | |
var lines = []; | |
tree.forEach(function (info){ | |
info_object_to_lines(info, lines, deep); | |
}); | |
return lines.join('\n'); | |
} | |
function info_object_to_lines(info, lines, deep=0) { | |
lines.push(output_title_line(info, deep)); | |
output_children_lines(info, lines, deep+1); | |
} | |
function output_title_line(info, deep) { | |
return make_indent(deep) + '- [ ] [' + info.title + '](' + info.link + ')' | |
} | |
function output_children_lines(info, lines, deep) { | |
if (!info) return ; | |
if (!info.children) return ; | |
if (info.children.length == 0) return ; | |
return info.children.map(child => info_object_to_lines(child, lines, deep)) | |
} | |
function make_indent(deep) { | |
return repeat(' ', deep); | |
} | |
function repeat(str, len) { | |
return Array(len).fill(str, 0, len).join(''); | |
} | |
var tree = get_li_elts(document.querySelector('div#tree-div > ul')); | |
var text = to_markdown(tree); | |
var pre = '<pre>' + text + '</pre>'; | |
document.body.innerHTML = pre; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment