pipe<T, R> function

R Function(T) pipe<T, R>(
  1. List<R Function(dynamic)> fns
)

Pipe (chain unary functions). Compose (f(g(x))). Once (run block only once). Roadmap #246-248. Builds a function that threads its input left-to-right through fns, passing each result to the next. Throws a StateError if the final value is not assignable to R.

Example:

final f = pipe<int, int>([(x) => x + 1, (x) => x * 2]);
f(3); // 8

Implementation

/// Builds a function that threads its input left-to-right through [fns],
/// passing each result to the next. Throws a [StateError] if the final value
/// is not assignable to [R].
///
/// Example:
/// ```dart
/// final f = pipe<int, int>([(x) => x + 1, (x) => x * 2]);
/// f(3); // 8
/// ```
R Function(T) pipe<T, R>(List<R Function(dynamic)> fns) => (T x) {
  dynamic v = x;
  for (final R Function(dynamic) f in fns) {
    v = f(v);
  }
  if (v is R) return v;
  throw StateError('pipe: result is ${v.runtimeType}, expected $R');
};