All files / hummus-toc/src getTOCText.js

100% Statements 21/21
100% Branches 3/3
100% Functions 4/4
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 251x 4x 320x 320x 296x   320x   4x 28x 320x 320x 320x 320x 24x 24x 24x 24x   296x 296x   4x    
module.exports = (outline, tocPageCount) => {
  const getTabs = tabLevel => {
    let output=''
    for (let i = 0; i < tabLevel; ++i) {
      output += '  '
    }
    return output
  }
  const lineLength = 60
  const makeTOC = (outln, tabLevel, prefix = '') => outln.reduce((acc, curr, idx) => {
    const entry = `${getTabs(tabLevel)}${prefix}${idx+1} ${curr.title}`
    const paddingLength = lineLength - String(curr.page+tocPageCount+1).length
    const line = `${entry.padEnd(paddingLength, '.')}${curr.page+tocPageCount+1}`
    if (curr.children) {
      acc.push({line, page: curr.page})
      const merged = acc.concat(makeTOC(curr.children, ++tabLevel, `${idx+1}.`))
      tabLevel--
      return merged
    }
    acc.push({line, page: curr.page})
    return acc
  }, [])
  return makeTOC(outline, 0)
}