private static void updateListenerChildren()

in stetho/src/main/java/com/facebook/stetho/inspector/elements/Document.java [495:546]


  private static void updateListenerChildren(
      ChildEventingList listenerChildren,
      List<Object> newChildren,
      Accumulator<Object> insertedElements) {
    int index = 0;
    while (index <= listenerChildren.size()) {
      // Insert new items that were added to the end of the list
      if (index == listenerChildren.size()) {
        if (index == newChildren.size()) {
          break;
        }

        final Object newElement = newChildren.get(index);
        listenerChildren.addWithEvent(index, newElement, insertedElements);
        ++index;
        continue;
      }

      // Remove old items that were removed from the end of the list
      if (index == newChildren.size()) {
        listenerChildren.removeWithEvent(index);
        continue;
      }

      final Object listenerElement = listenerChildren.get(index);
      final Object newElement = newChildren.get(index);

      // This slot has exactly what we need to have here.
      if (listenerElement == newElement) {
        ++index;
        continue;
      }

      int newElementListenerIndex = listenerChildren.indexOf(newElement);
      if (newElementListenerIndex == -1) {
        listenerChildren.addWithEvent(index, newElement, insertedElements);
        ++index;
        continue;
      }

      // TODO: use longest common substring to decide whether to
      //       1) remove(newElementListenerIndex)-then-add(index), or
      //       2) remove(index) and let a subsequent loop iteration do add() (that is, when index
      //          catches up the current value of newElementListenerIndex)
      //       Neither one of these is the best strategy -- it depends on context.

      listenerChildren.removeWithEvent(newElementListenerIndex);
      listenerChildren.addWithEvent(index, newElement, insertedElements);

      ++index;
    }
  }