memoized 1.2.4 copy "memoized: ^1.2.4" to clipboard
memoized: ^1.2.4 copied to clipboard

outdated

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
}
7
likes
0
pub points
86%
popularity

Publisher

verified publishersylfree.com

Useful function wrappers for avoiding unnecessary computation. it makes the function return a memoized(cached) value.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

to_string_pretty

More

Packages that depend on memoized