modifyAt<T> function

Option<ImmutableList<T>> Function(ImmutableList<T>) modifyAt<T>(
  1. int index,
  2. T modify(
    1. T
    )
)

Returns a function that takes an ImmutableList<T> and modifies a specified item at the given index using the provided modify function.

If the given index is out of bounds of the list, None<ImmutableList<T>>() is returned. Otherwise, a new ImmutableList<T> with the modified item is returned.

Usage:

var myList = ImmutableList([1, 2, 3, 4, 5]);
var incrementItemAt2 = modifyAt<int>(2, (item) => item + 1);
var newListOption = incrementItemAt2(myList); // Returns option containing ImmutableList([1, 2, 4, 4, 5])
  • Parameters:
    • index: The index of the item to be modified.
    • modify: A function that takes an item of type T and returns the modified item of type T.
  • Returns: A function that processes an ImmutableList<T> and returns an Option<ImmutableList<T>> containing the list with the modified item, or None<ImmutableList<T>>() if the index is out of bounds.

Implementation

option.Option<ImmutableList<T>> Function(ImmutableList<T>) modifyAt<T>(
    int index, T Function(T) modify) {
  return (ImmutableList<T> list) {
    if (index < 0 || index >= list.items.length) {
      return option.None<ImmutableList<T>>();
    }
    final List<T> newListItems = List.from(list.items);
    newListItems[index] = modify(newListItems[index]);
    return option.of(ImmutableList(newListItems));
  };
}