Skip to content

IGListDiff Result Cannot Correctly Transform Original Array to Target Array #1627

Open
@taohailong

Description

@taohailong

Description:

Using the result of IGListDiff to transform the original array into the target array does not produce the expected output.

Reproduction Steps:

NSArray<NSString*> *oriList = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H",@"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P",@"Q", @"R", @"S", @"T", @"U", @"V"];
NSArray *newList = @[@"J", @"E", @"C", @"O", @"Q", @"H", @"L", @"G", @"W", @"K"];

IGListIndexSetResult *diff = IGListDiff(oriList, newList, IGListDiffEquality);
NSMutableArray<NSString*> *modifyArray = [oriList mutableCopy];

// 1. Perform deletions
NSArray *deleteModels = [modifyArray objectsAtIndexes:diff.deletes];
[deleteModels enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSUInteger removeIndex = [modifyArray indexOfObject:obj];
    NSAssert(removeIndex != NSNotFound, @"Delete element error index %ld, element %@", idx, obj);
    [modifyArray removeObject:obj];
}];

// 2. Perform insertions
[diff.inserts enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
    id insertModel = [newList objectAtIndex:idx];
    NSAssert(insertModel != nil, @"Insert element is nil at index %ld", idx);
    [modifyArray insertObject:insertModel atIndex:idx];
}];

// 3. Perform moves
__auto_type moveArray = [diff.moves sortedArrayUsingComparator:^NSComparisonResult(IGListMoveIndex * _Nonnull obj1, IGListMoveIndex * _Nonnull obj2) {
    return obj1.from > obj2.from ? NSOrderedDescending : NSOrderedAscending;
}];

[moveArray enumerateObjectsUsingBlock:^(IGListMoveIndex * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    id element = oriList[obj.from];
    NSUInteger toIndex = obj.to;
    NSUInteger currentIndex = [modifyArray indexOfObject:element];
    if (currentIndex != toIndex) {
        [modifyArray removeObject:element];
        if (toIndex < modifyArray.count) {
            [modifyArray insertObject:element atIndex:toIndex];
        } else {
            [modifyArray addObject:element];
        }
    }
}];

NSLog(@"Result: %@", modifyArray);

Expected Output:

modifyArray should be:
[@"J", @"E", @"C", @"O", @"Q", @"H", @"L", @"G", @"W", @"K"]


Actual Output:

modifyArray is:
[@"J", @"E", @"C", @"O", @"Q", @"L", @"H", @"G", @"W", @"K"]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions