Abion47 / darq

A port of .NET's LINQ IEnumerable functions to Dart.
MIT License
85 stars 9 forks source link

default value null #14

Closed tofutim closed 2 years ago

tofutim commented 2 years ago

Here tokens is a List. I am not able to set default to be "null" though it should be possible. What if the where brings up nothing, List of size zero?

        var firstLineBreakGoingBackwards = tokens
            .where((t) => t.ix < startIx && t.isLineBreak)
            .orderByDescending((t) => t.ix)
            .firstOrDefault(defaultValue: null);

image

For C#,

public static TSource? FirstOrDefault<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

so likewise we ought to have

extension FirstOrDefaultExtension<T> on Iterable<T> {
  /// Returns the first element in the iterable.
  ///
  /// If the iterable is empty, the value specified by [defaultValue] will be
  /// returned instead. If [defaultValue] is omitted, the returned value will be
  /// `null`.
  ///
  /// Example:
  ///
  ///     void main() {
  ///       final list = <int>[];
  ///       final result = list.firstOrDefault(defaultValue: -1);
  ///
  ///       // Result: -1
  ///     }
  T? firstOrDefault({required T? defaultValue}) {
    if (isEmpty) return defaultValue;
    return first;
  }
}