实现说明
各个操作都建立在顶层绑定之上:lastPush、lastPrIndex。
使用要点
- 演示输出是带标签的(
last pr index:),每个操作都会留下自己的一行标注。
常见问题
依赖情况复杂吗?
一点也不复杂:零依赖,没有要锁版本或审计的东西。 状态都挂在模块顶层:lastPush、lastPrIndex。
核心语句
const lastPrIndex = events.findLastIndex((e) => e.kind === 'pr');
const lastPush = events.findLast((e) => e.kind === 'push');
代码示例
const events: ReadonlyArray<{ kind: string; at: number }> = [
{ kind: 'push', at: 10 },
{ kind: 'pr', at: 20 },
{ kind: 'push', at: 30 },
];
// 从尾部向前扫描:返回最后一个匹配项或 undefined
const lastPush = events.findLast((e) => e.kind === 'push');
console.log(lastPush?.at, '| kind:', lastPush?.kind);
// findLastIndex 给出最后一个匹配的下标,无匹配返回 -1
const lastPrIndex = events.findLastIndex((e) => e.kind === 'pr');
console.log('last pr index:', lastPrIndex);
// 无匹配时的兜底:?? 后备值让 undefined 变成显式结果
console.log(events.findLast((e) => e.kind === 'tag') ?? 'none');