67 lines
1.2 KiB
JavaScript
67 lines
1.2 KiB
JavaScript
/**
|
|
* @author Titus Wormer
|
|
* @copyright 2015 Titus Wormer
|
|
* @license MIT
|
|
* @module mdast:toc
|
|
* @fileoverview Generate a Table of Contents (TOC) from a given Markdown file.
|
|
*/
|
|
|
|
/* Expose. */
|
|
module.exports = contents;
|
|
|
|
/* Dependencies */
|
|
var list = require('./list');
|
|
var insert = require('./insert');
|
|
|
|
/**
|
|
* Transform a list of heading objects to a markdown list.
|
|
*
|
|
* @param {Array.<Object>} map - Heading-map to insert.
|
|
* @param {boolean?} [tight] - Prefer tight list-items.
|
|
* @return {Object} - List node.
|
|
*/
|
|
function contents(map, tight) {
|
|
var minDepth = Infinity;
|
|
var index = -1;
|
|
var length = map.length;
|
|
var table;
|
|
|
|
/*
|
|
* Find minimum depth.
|
|
*/
|
|
|
|
while (++index < length) {
|
|
if (map[index].depth < minDepth) {
|
|
minDepth = map[index].depth;
|
|
}
|
|
}
|
|
|
|
/*
|
|
* Normalize depth.
|
|
*/
|
|
|
|
index = -1;
|
|
|
|
while (++index < length) {
|
|
map[index].depth -= minDepth - 1;
|
|
}
|
|
|
|
/*
|
|
* Construct the main list.
|
|
*/
|
|
|
|
table = list();
|
|
|
|
/*
|
|
* Add TOC to list.
|
|
*/
|
|
|
|
index = -1;
|
|
|
|
while (++index < length) {
|
|
insert(map[index], table, tight);
|
|
}
|
|
|
|
return table;
|
|
}
|