memoized 1.1.1 copy "memoized: ^1.1.1" to clipboard
memoized: ^1.1.1 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);
}

String time<V>(V Function() fn) {
  final watch = Stopwatch()..start();
  watch.start();
  final result = fn();
  watch.stop();
  final elapsed = '${watch.elapsedMilliseconds}ms';
  return '[${elapsed.padLeft(6)}] $result returned.';
}

void main() {
  Iterable<int> numbers = 1.to(30000000);
  final calculateSum = (() => numbers.sum()).memo;

  print('===== Memoized =====');
  print(time(calculateSum));
  print(time(calculateSum)); // It returns the memoized value.

  numbers = 1.to(45000000);
  calculateSum.requestUpdate(); // Update the function called.
  print(time(calculateSum)); // Recomputed at this point.

  int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
  }

  final fibMemo = Memoized1<BigInt, BigInt>(
    (n, self) {
      if (n <= BigInt.one) return n;
      return self(n - BigInt.one) + self(n - BigInt.two);
    },
  );

  final countVowelMemo = Memoized1<int, String>((str, self) {
    int count = 0;
    for (int i = 0; i < str.length; i++) {
      if ("aeiouAEIOU".contains(str[i])) count++;
    }
    return count;
  });

  print('\n===== Memoized1 =====');
  print(time(() => fibMemo(BigInt.parse('300'))));
  print(time(() => countVowelMemo('aeiouAeiou')));
}
11
likes
0
points
923
downloads

Publisher

verified publishersylfree.com

Weekly Downloads

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