ego-tree icon indicating copy to clipboard operation
ego-tree copied to clipboard

How to insert child at index?

Open jessegrosjean opened this issue 7 years ago • 1 comments

I'd like to insert a child into a NodeMut at a specified index. Seems like it should be easy, but I can't figure it out. Keep running into lifetime problems.

My non-working code is:

fn insert_child_at_index<'a, T>(parent: &'a mut NodeMut<'a, T>, value: T, index: usize) -> NodeMut<'a, T> {
  if let Some(insert_before_id) = parent.tree.get(parent.id).unwrap().children().skip(index).next().map(|n| n.id) {
    parent.tree.get_mut(insert_before_id).unwrap().insert_before(value)
  } else {
    parent.append(value)
  }
}

The logic (for now) is to insert before child node at given index if child node exists, otherwise insert at end. In final API it probably makes more sense to throw error if index is beyond count, but I'm trying to keep example code simple as possible at moment.

Any tips on how to get this working?

jessegrosjean avatar Oct 02 '18 19:10 jessegrosjean

Quite possibly there's a simple way using existing API, but I couldn't figure it out. In the meantime I've created this pull request that adds the API that I really wanted in the first place: https://github.com/programble/ego-tree/pull/15

jessegrosjean avatar Oct 03 '18 15:10 jessegrosjean