UNPKG

aubade

Version:

markdown, orchestrated.

32 lines (31 loc) 1.15 kB
export function chain(items, options) { const { key = 'flank', group = () => 'default', sorter, breakpoint, transform = ({ slug, title }) => ({ slug, title }), finalize = (groups) => Object.values(groups).flat(), } = options; const groups = {}; for (const item of items) { const key = group(item); if (key == null) continue; groups[key] = groups[key] || []; groups[key].push(item); } for (const name in groups) { sorter && groups[name].sort(sorter(name)); groups[name] = process(groups[name]); } return finalize(groups); function process(array) { for (let idx = 0; idx < array.length; idx++) { const [back, next] = [array[idx - 1], array[idx + 1]]; if (!back && !next) continue; array[idx][key] = array[idx][key] || {}; if (back) array[idx][key].back = transform(back); if (breakpoint && breakpoint(next)) return array; if (next) array[idx][key].next = transform(next); } return array; } }