Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. /* jshint esnext: true */
  2.  
  3. // fn should be a repeat-access function that returns an m.request.
  4. export default memo( fn => {
  5. let outcome;
  6. let pending;
  7. let resolved = false;
  8.  
  9. return ( ...args ) => {
  10. // If the pendant is executed with arguments, we call fn.
  11. // If it has already been invoked, we return the previous
  12. // outcome.
  13. if( !pending || args.length ){
  14. // Outcome is an m.prop and a thennable
  15. outcome = fn( ...args );
  16. pending = true;
  17.  
  18. outcome.then( () => pending = false );
  19.  
  20. if( !resolved ) outcome.then( () => resolved = true );
  21. }
  22.  
  23. // Return the outcome, extended with state accessors
  24. return Object.assign( outcome, {
  25. pending : () => pending,
  26. resolved : () => resolved,
  27. // valueOf avoids the need for `myPendant()()`,
  28. // which becomes `myPendant().valueOf()`.
  29. valueOf : () => outcome()
  30. } );
  31. }
  32. } )
  33.  
  34. // Returns a function that will return previously cached results
  35. // (instead of executing again) if the input is identical to that
  36. // of a previous execution
  37. function memo( fn ){
  38. var cache = WeakMap();
  39.  
  40. return input => cache.has( input )
  41. ? cache.get( input )
  42. : cache.set( input, fn( input ) ).get( input );
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement