Skip to content

Instantly share code, notes, and snippets.

@lski
Created October 27, 2019 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lski/7454070fa07f91ddd1454b7a38e529b6 to your computer and use it in GitHub Desktop.
Save lski/7454070fa07f91ddd1454b7a38e529b6 to your computer and use it in GitHub Desktop.
Converts a list of objects to a Markdown table
export const toMarkdownTable = (keys = null) => (list) => {
if (list == null) throw new Error('The list needs to be an array');
if (list.length === 0) return '';
keys = keys || Object.keys(list[0]);
if (keys.length === 0) return '';
headers = toMarkdownHeaders(keys);
body = list.map(obj => toMarkdownRow(obj, keys)).join('\n');
return headers + '\n' + body;
};
const toMarkdownHeaders = (headers) => {
let columnHeaders = [];
let underlines = [];
for (const header of headers) {
columnHeaders.push(`${header}`);
underlines.push(''.padEnd(header.length, '-'));
}
return `| ${columnHeaders.join(' | ')} |\n|-${underlines.join('-|-')}-|`;
};
const toMarkdownRow = (obj, keys) => {
let output = [];
for (const key of keys) {
output.push(obj[key]);
}
return `| ${output.join(' | ')} |`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment