memoized 1.2.1
memoized: ^1.2.1 copied to clipboard
Useful function wrappers for avoiding unnecessary computation. it makes the function return a memoized(cached) value.
example/memoized_example.dart
import 'package:memoized/memoized.dart';
extension RangeGenExt on int {
Iterable<int> to(int target) sync* {
int start = this;
while (start <= target) {
yield start;
start++;
}
}
}
extension IterableNumberExt on Iterable<int> {
int sum() => reduce((value, element) => value + element);
}
void time<V>(V Function() fn) {
final watch = Stopwatch()..start();
watch.start();
final result = fn();
watch.stop();
final elapsed = '${watch.elapsedMilliseconds} ms';
print('[${elapsed.padLeft(7)}] $result returned.');
}
Future<void> timeAsync<V>(Future<V> future) async {
final watch = Stopwatch()..start();
watch.start();
final result = await future;
watch.stop();
final elapsed = '${watch.elapsedMilliseconds} ms';
print('[${elapsed.padLeft(7)}] $result returned.');
}
void main() async {
Iterable<int> numbers = 1.to(30000000);
final calculateSum = (() => numbers.sum()).memo;
print('===== Memoized =====');
time(calculateSum);
time(calculateSum); // It returns the memoized value.
late final Memoized1<int, int> fib;
fib = Memoized1((int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
});
late final Memoized1Async<String, String> fetchDocument;
fetchDocument = Memoized1Async((url) async {
await Future.delayed(const Duration(seconds: 2));
if (url == 'hello') return 'hello, memoized';
return 'welcome';
});
print('\n===== Memoized1 =====');
time(() => fib(90));
await timeAsync(fetchDocument('hello'));
fetchDocument.expire('hello');
await timeAsync(fetchDocument('hello')); // returned immediately
await timeAsync(fetchDocument('hello')); // returned immediately
await timeAsync(fetchDocument('test'));
await timeAsync(fetchDocument('test')); // returned immediately
}