pin-diary-5のutil.tsの解析
linesにappendsを追加する関数
footersをこれに渡す際には予め.reverse()で行の並びを逆にしてから渡している
code:util.ts
export function patchLines(lines: string[], appends: string[]): string[] {
let index = 0; // 確認済みのlinesの行数
const result = [] as string[];
ここのfor文でlinesとappendの比較とappendの挿入を行っている
appendsを1行ごとに比較しているが、そこまで複雑に比較する必要は無いように思える
code:util.ts
for (let i = 0; i < appends.length; i++) {
確認中の行がindex以降で、かつline行と挿入しようとしている行が同一な行の位置を調べている
行頭のインデントを無視して内容で判別しようとしている?
code:util.ts
const pos = lines.findIndex((line, j) => j >= index && line.trim() === appendsi.trim()); if (pos < 0) {
一致する行が見つからなかった場合は末尾に挿入
code:util.ts
continue;
}
result.push(...lines.slice(index, pos + 1));
index = pos + 1;
}
result.push(...lines.slice(index));
return result;
}
今回は関係ない
code:util.ts
export function findSplitIndex(lines: string[], query: string[]) {
let index = -1;
for (const text of query) {
const pos = lines.findIndex((line, j) => j > index && line.trim() === text.trim());
if (pos < 0) return -1;
index = pos;
}
return index;
}
ちょっと書き直す
反映した
これ以上ここのソースコードは更新しない
code:utils-dev.ts
export function patchLines(
lines: string[],
appends: string[],
position: ("head" | "tail") = "head",
): string[] {
let appendsIndex = 0;
for (const linesIndex in lines) {
if (appendsIndex == appends.length - 1) {
// appendsと完全に一致するパターンが発見されたので行を挿入せずに終了する
return lines;
}
appendsIndex += 1;
} else {
appendsIndex = 0;
}
}
// 一致するパターンが見つからなかった場合はappendsを挿入する
switch(position) {
case "head":
case "tail":
}
}
手を付けないので分離
フォーマットと本文に空行を入れる際に必要なのでこいつも書き換える
空行をフォーマットとして認識させたくないので必要
見つからなかった場合は-1ではなくnullを返すようにした
code:utils-dev.ts
/** queryに合致するlinesの終了行を返す */
export function findSplitIndex(
lines: string[],
query: string[],
): number | null {
let queryCount = 0;
for (const lineIndex in lines) {
if (queryCount == query.length - 1) return Number(lineIndex);
++queryCount;
}
}
return null;
}