spliceList method
Changes the contents of the list at path
by removing deleteCount
items at index
, and inserting values
in-place. Returns the elements
that are deleted.
index
and deleteCount
must be non-negative and index
+ deleteCount
must be no greater than the list's length.
Throws a ArgumentError if the element at the given path is not a
YamlList
or if the path is invalid.
Throws an AliasException if a node on path
is an alias or anchor.
Example:
final doc = YamlEditor('[Jan, March, April, June]');
doc.spliceList([], 1, 0, ['Feb']); // [Jan, Feb, March, April, June]
doc.spliceList([], 4, 1, ['May']); // [Jan, Feb, March, April, May]
Implementation
Iterable<YamlNode> spliceList(Iterable<Object?> path, int index,
int deleteCount, Iterable<Object?> values) {
final list = _traverseToList(path, checkAlias: true);
RangeError.checkValueInInterval(index, 0, list.length);
RangeError.checkValueInInterval(index + deleteCount, 0, list.length);
final nodesToRemove = list.nodes.getRange(index, index + deleteCount);
// Perform addition of elements before removal to avoid scenarios where
// a block list gets emptied out to {} to avoid changing collection styles
// where possible.
// Reverse [values] and insert them.
final reversedValues = values.toList().reversed;
for (final value in reversedValues) {
insertIntoList(path, index, value);
}
for (var i = 0; i < deleteCount; i++) {
remove([...path, index + values.length]);
}
return nodesToRemove;
}