/// <summary>Returns new tree with added or updated value for specified key.</summary> /// <param name="key">Key</param> <param name="value">Value</param> /// <param name="updateValue">(optional) Delegate to calculate new value from and old and a new value.</param> /// <returns>New tree.</returns> public ImMap <TValue> AddOrUpdate(int key, TValue value, ImUpdateDelegate <TValue> updateValue) => AddOrUpdateImpl(key, value, false, updateValue);
private ImMap <TValue> AddOrUpdateImpl(int key, TValue value, bool updateOnly, ImUpdateDelegate <TValue> update) { return(Height == 0 ? // tree is empty (updateOnly ? this : new ImMap <TValue>(key, value)) : (key == Key ? // actual update new ImMap <TValue>(key, update == null ? value : update(Value, value), Left, Right) : (key < Key // try update on left or right sub-tree ? new ImMap <TValue>(Key, Value, Left.AddOrUpdateImpl(key, value, updateOnly, update), Right) : new ImMap <TValue>(Key, Value, Left, Right.AddOrUpdateImpl(key, value, updateOnly, update))) .KeepBalance())); }