compose
T Function(T)
compose<
Composes single-argument functions from right to left.
The rightmost function can take multiple arguments as it provides the signature for the resulting composite function.
Example:
final add = (int x) => x + 1;
final multiply = (int x) => x * 2;
final subtract = (int x) => x - 3;
// Without compose: subtract(multiply(add(5)))
// With compose: compose([subtract, multiply, add])(5)
final composed = compose([subtract, multiply, add]);
print(composed(5)); // ((5 + 1) * 2) - 3 = 9
This is mainly useful for composing store enhancers.
Implementation
T Function(T) compose<T>(List<T Function(T)> functions) {
if (functions.isEmpty) return (arg) => arg;
if (functions.length == 1) return functions.first;
return functions.reduce(
(a, b) =>
(arg) => a(b(arg)),
);
}