memoized 1.1.2
memoized: ^1.1.2 copied to clipboard
Useful function wrappers for avoiding unnecessary computation. it makes the function return a memoized(cached) value.
Installing #
dependencies:
memoized:
import 'package:memoized/memoized.dart';
Memoized #
Wrap a function to store the previously computed value and return this value on the next call.
-
Basic
Iterable<int> numbers = 1.to(30000000); final calculateSum = (() => numbers.sum()).memo; print(time(calculateSum)); print(time(calculateSum)); // It returns the memoized value.
-
Update
Iterable<int> numbers = 1.to(30000000); final calculateSum = (() => numbers.sum()).memo; numbers = 1.to(9043483); calculateSum.update(); // recomputed
-
Lazy Update
Iterable<int> numbers = 1.to(30000000); final calculateSum = (() => numbers.sum()).memo; print(calculateSum()); numbers = 1.to(9043483); calculateSum.requestUpdate(); // not computed numbers = 1.to(45000000); calculateSum.requestUpdate(); // not computed final value = calculateSum() // recomputed at this point.
-
in Class #
class IntervalTimer { final List<Duration> timers = [/* durations */]; late final totalDuration = _totalDurationImpl.memo; Duration _totalDurationImpl() => timers.fold<Duration>( Duration.zero, (p, v) => p + v ); }
Memoized1 #
Decorator to wrap a function with a memoizing callable that saves up to the capacity most recent calls.
-
fibonacci
// Memoized1<RetrunType, ArgumentType> final fibMemo = Memoized1<BigInt, BigInt>((n, self) { if (n <= BigInt.one) return n; return self(n - BigInt.one) + self(n - BigInt.two); }); // returns 222232244629420445529739893461909967206666939096499764990979600 // very quickly print(fibMemo(BigInt.parse('300')));
-
count vowels
final countVowelMemo = Memoized1<int, String>((str, _) { int count = 0; for (int i = 0; i < str.length; i++) { if ("aeiouAEIOU".contains(str[i])) count++; } return count; });
-
Cache capacity
final fibMemo = Memoized1<BigInt, BigInt>( (n, self) { if (n <= BigInt.one) return n; return self(n - BigInt.one) + self(n - BigInt.two); }, capacity: 1, // modified, default == 128 ); // Oh, god print(fibMemo(BigInt.parse('300')));