/** * @fileOverview * * 有序维护选区 */ export interface Identifiable { id: string | number; } /** * 保证 selection 保持与 records 有相同的偏序关系,查找插入位置 */ function findInsertPosition( records: T[], selection: T[], item: T ): number { const recordIndex = records.indexOf(item); let ri = 0; let si = 0; while (records[ri] && selection[si]) { if (ri === recordIndex) break; if (records[ri] === selection[si] || records[ri].id === selection[si].id) { si += 1; } ri += 1; } return si; } /** * 插入到选区中,保持与 records 相同的偏序顺序 */ export function selectionInsert( records: T[], selection: T[], item: T ): T[] { const newSelection = selection ? selection.slice() : []; const index = newSelection.indexOf(item); if (index === -1) { const insertIndex = findInsertPosition(records, newSelection, item); newSelection.splice(insertIndex, 0, item); } return newSelection; } /** * 从选取中删除 */ export function selectionRemove( records: T[], selection: T[], item: T ): T[] { const newSelection = selection.slice(); const index = newSelection.indexOf(item); if (index > -1) { newSelection.splice(index, 1); } return newSelection; }