テーブル記法を箇条書きに変換する
#UserScript
GPT-4.iconがよくテーブル記法で返してくるので
https://gyazo.com/c28a8ef7919af7c6d589af292eb0384f
code:script.js
scrapbox.PopupMenu.addButton({
title: 'table-to-bullets',
onClick: convertTableToBullets,
});
function convertTableToBullets(input) {
const lines = input.split("\n");
return processLines(lines);
}
const processLines = (lines) => {
let tableBaseIndent = null;
const processedLines = lines
.map((line) => {
const { output, newTableIndent } = processLine(line, tableBaseIndent);
tableBaseIndent = newTableIndent;
return { output, isTable: getTableMatch(line) !== null };
})
.filter(({ output, isTable }) => output !== "" || !isTable)
.map(({ output }) => output);
return processedLines.join("\n");
};
const processLine = (line, tableIndent) => {
const tableMatch = getTableMatch(line);
// table:行 - 削除してネスト数を記憶
if (tableMatch) {
return {
output: "",
newTableIndent: tableMatch1.length,
};
}
// テーブル内の行
if (tableIndent !== null) {
return processTableLine(line, tableIndent);
}
// テーブル外の行はそのまま
return {
output: line,
newTableIndent: null,
};
};
const processTableLine = (line, tableIndent) => {
const lineIndent = indentLevel(line);
// テーブル終了判定(ネスト数が同じかそれより少ない)
if (lineIndent <= tableIndent) {
return {
output: line,
newTableIndent: null,
};
}
const cells = line.substring(lineIndent).split("\t");
const bulletLines = cells.map((cell, index) => {
const indent = " ".repeat(index === 0 ? 0 : 1);
return indent + cell;
});
return {
output: indent(bulletLines, tableIndent).join("\n"),
newTableIndent: tableIndent,
};
};
const indent = (lines, indent) =>
lines.map((line) => " ".repeat(indent) + line);
const indentLevel = (line) => {
const match = line.match(/^(\s*)/);
return match ? match1.length : 0;
};
const getTableMatch = (line) => line.match(/^(\s*)table:(.*)$/);