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

outdated

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<Duratio>(
          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

    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, self) {
      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')));
    
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