Last active
March 17, 2021 19:12
-
-
Save amsterdamharu/2dde4a6f531251f3769206ee44458af7 to your computer and use it in GitHub Desktop.
group action and function result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//group promise returning function | |
const createGroup = (cache) => ( | |
fn, | |
getKey = (...x) => JSON.stringify(x) | |
) => (...args) => { | |
const key = getKey(args); | |
let result = cache.get(key); | |
if (result) { | |
return result; | |
} | |
//no cache | |
result = Promise.resolve(fn.apply(null, args)).then( | |
(r) => { | |
cache.resolved(key); //tell cache promise is done | |
return r; | |
}, | |
(e) => { | |
cache.resolve(key); //tell cache promise is done | |
return Promise.reject(e); | |
} | |
); | |
cache.set(key, result); | |
return result; | |
}; | |
//thunk action creators are not (...args)=>result but | |
// (...args)=>(dispatch,getState)=>result | |
// so here is how we group thunk actions | |
const createGroupedThunkAction = (thunkAction, cache) => { | |
const group = createGroup( | |
cache | |
)((args, dispatch, getState) => | |
thunkAction.apply(null, args)(dispatch, getState) | |
); | |
return (...args) => (dispatch, getState) => { | |
return group(args, dispatch, getState); | |
}; | |
}; | |
//permanent memory cache store creator | |
const createPermanentMemoryCache = (cache = new Map()) => { | |
return { | |
get: (key) => cache.get(key), | |
set: (key, value) => cache.set(key, value), | |
resolved: (x) => x, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment