使用时间戳实现幂等时如何检测对象数组中的重复时间戳?
数组对象stamp属性重复检测实现方案
推荐使用Set结构实现检测,相比嵌套循环性能更优,时间复杂度为O(n),适配任意长度的数组:
// 检测是否存在重复stamp,存在返回true,不存在返回false function hasDuplicateStamp(arrayItem: Item[]): boolean { const stampSet = new Set(arrayItem.map(item => item.stamp)); return stampSet.size < arrayItem.length; }
使用方法
在数据发送前调用该方法,返回true时触发告警终止发送即可:
if (hasDuplicateStamp(arrayItem)) { // 自定义告警逻辑,例如弹窗提示、输出错误日志 console.error('存在重复时间戳,数据发送已阻断'); return; } // 后续正常发送数据的逻辑
如果需要定位具体重复的时间戳值,可以使用Map统计每个stamp的出现次数:
function getDuplicateStampList(arrayItem: Item[]): number[] { const stampCountMap = new Map<number, number>(); arrayItem.forEach(item => { const currentCount = stampCountMap.get(item.stamp) || 0; stampCountMap.set(item.stamp, currentCount + 1); }); // 筛选所有出现次数大于1的时间戳 return Array.from(stampCountMap.entries()) .filter(([stamp, count]) => count > 1) .map(([stamp]) => stamp); }
内容的提问来源于stack exchange,提问作者olivier
相关产品推荐
相关产品推荐

