Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* jshint esnext: true */
- // fn should be a repeat-access function that returns an m.request.
- export default memo( fn => {
- let outcome;
- let pending;
- let resolved = false;
- return ( ...args ) => {
- // If the pendant is executed with arguments, we call fn.
- // If it has already been invoked, we return the previous
- // outcome.
- if( !pending || args.length ){
- // Outcome is an m.prop and a thennable
- outcome = fn( ...args );
- pending = true;
- outcome.then( () => pending = false );
- if( !resolved ) outcome.then( () => resolved = true );
- }
- // Return the outcome, extended with state accessors
- return Object.assign( outcome, {
- pending : () => pending,
- resolved : () => resolved,
- // valueOf avoids the need for `myPendant()()`,
- // which becomes `myPendant().valueOf()`.
- valueOf : () => outcome()
- } );
- }
- } )
- // Returns a function that will return previously cached results
- // (instead of executing again) if the input is identical to that
- // of a previous execution
- function memo( fn ){
- var cache = WeakMap();
- return input => cache.has( input )
- ? cache.get( input )
- : cache.set( input, fn( input ) ).get( input );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement