ai-query对接新版freesun-agent接口的分支
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

42 lines
1.4 KiB

/**
* @param {string} markdown - Markdown 表格的字符串。
* @returns {{headers: string[], rows: string[][]}} - 包含表头数组和数据行二维数组的对象。
*/
module.exports.markdownTableToArray = function (markdown) {
// 1. 使用换行符分割表格的行,并过滤掉空行
const rows = markdown.trim().split('\n').filter(row => row.trim() !== '');
// 2. 处理每一行
const data = rows.map(row => {
let r = row.trim();
// 移除行首和行尾的 '|' 符号(如果存在)
// 这样做是为了确保 split('|') 能正确处理内容,
// 即使表格行的开头和结尾没有 '|' 也能工作。
if (r.startsWith('|')) {
r = r.substring(1);
}
if (r.endsWith('|')) {
r = r.substring(0, r.length - 1);
}
// 3. 用管道符 '|' 分割每行,并去除每个单元格的首尾空格
// 这里不再使用 filter,因此空单元格会保留为 ""
return r.split('|').map(cell => cell.trim());
});
// 4. 获取并移除表头
const headers = data.shift() || []; // 如果没有数据则返回空数组
// 5. 检查并移除分隔线
// 分隔线行中的每个单元格都必须包含至少一个 '-'
if (data.length > 0 && data[0].every(cell => cell.includes('-'))) {
data.shift(); // 移除分隔线
}
// 6. 返回结果
return {
headers: headers,
rows: data
};
}