Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. void main() {
  2. var add = memoize((a, b) => a + b);
  3. var x = add(1, 2);
  4. var y = add(1, 2);
  5. }
  6.  
  7. class _FunctionCall {
  8. final List<dynamic> positional;
  9. final Map<Symbol, dynamic> named;
  10.  
  11. _FunctionCall(this.positional, this.named);
  12.  
  13. int get hashCode => hashObjects([]..addAll(positional)..addAll(named.keys)..addAll(named.values));
  14. bool operator ==(obj) {
  15. if (obj is! _FunctionCall) return false;
  16. var indexes = new List.generate(obj.positional.length, (i) => i);
  17. return indexes.every((i) => positional[i] == obj.positional[i]);
  18. }
  19. }
  20.  
  21. memoize(Function input) {
  22. var cache = {};
  23. var capture = new _FunctionCapture((p, n) {
  24. var call = new _FunctionCall(p, n);
  25. if (cache.containsKey(call)) {
  26. print("Using Cache");
  27. return cache[call];
  28. } else {
  29. print("Placing in Cache");
  30. return cache[call] = Function.apply(input, p, n);
  31. }
  32. });
  33. return capture;
  34. }
  35.  
  36. class _FunctionCapture {
  37. final Function handler;
  38.  
  39. _FunctionCapture(this.handler);
  40.  
  41. @override
  42. noSuchMethod(Invocation inv) {
  43. print(inv);
  44. if (inv.isMethod && inv.memberName == #call) {
  45. return handler(inv.positionalArguments, inv.namedArguments);
  46. } else {
  47. return super.noSuchMethod(inv);
  48. }
  49. }
  50. }
  51.  
  52. /* Utils */
  53. int hashObjects(Iterable objects) =>
  54. _finish(objects.fold(0, (h, i) => _combine(h, i.hashCode)));
  55.  
  56. int _combine(int hash, int value) {
  57. hash = 0x1fffffff & (hash + value);
  58. hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
  59. return hash ^ (hash >> 6);
  60. }
  61.  
  62. int _finish(int hash) {
  63. hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
  64. hash = hash ^ (hash >> 11);
  65. return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement