Skip to content

moveItem doesn't reorder items properly #1

@httpdispatch

Description

@httpdispatch

fun moveItem(from: Int, to: Int) {
val fromEmoji = emojis[from]
emojis.removeAt(from)
if (to < from) {
emojis.add(to, fromEmoji)
} else {
emojis.add(to - 1, fromEmoji)
}
}

Imagine you move items from 0 position to 1

  • First your remove items at 0 position
  • Then you add item again to 0 position such as to > from and you add to to-1 position

The proper solution may be like this:

    fun moveItem(from: Int, to: Int) {
        val fromEmoji = emojis[from]
        emojis.removeAt(from)
        emojis.add(to, fromEmoji)    
    }

Test

@Test
    public void testMoveItem() {
        List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5);
        assertEquals(
                Arrays.asList(1, 0, 2, 3, 4, 5),
                moveItem(list, 0, 1));
        assertEquals(
                Arrays.asList(1, 2, 0, 3, 4, 5),
                moveItem(list, 0, 2));
        assertEquals(
                Arrays.asList(1, 2, 3, 4, 5, 0),
                moveItem(list, 0, 5));
        assertEquals(
                Arrays.asList(0, 1, 2, 3, 5, 4),
                moveItem(list, 5, 4));
        assertEquals(
                Arrays.asList(5, 0, 1, 2, 3, 4),
                moveItem(list, 5, 0));
        assertEquals(
                Arrays.asList(0, 1, 2, 4, 3, 5),
                moveItem(list, 3, 4));
        assertEquals(
                Arrays.asList(0, 1, 2, 4, 3, 5),
                moveItem(list, 4, 3));
    }

    public <T> List<T> moveItem(List<T> data, int from, int to) {
        data = new ArrayList<>(data);
        T item = data.get(from);
        data.remove(from);
        data.add(to, item);
        return data;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions