Cacher
Simple library for caching more complex function calls.
Can be used with react not to trigger rerendering by constantly creating new functors for components props.
Yet it has no dependencies to React or any other lib.
Installation
npm install --save Cacher
Simple Example
Let's say You have a component that receives a functor and renders N subcomponents.
Each subcomponent receives a callback which is the functor called with the subcomponents index.
You could write:
Component // ... { return ArraythispropsN; }
But this way every time You render Component each Subcomponent receives a new functor as callback and needs to rerender.
What if You could get the same functor every time You know You already had one like that?
Now you can! :)
; Component // ... cacher = ; { return ArraythispropsN; }
Voilà!
The first time this.cacher is called with an index it creates one callback function and returns it.
Every next time for the same index it just returns the one created before (same object/reference).
Object Oriented example
You can also add a context to the main functor.
Just use
to make Cacher call
object.functor(index)
instead of functor(index)
.
Multiply callbacks example
Cacher is configurable to accept an additional function (called action) aside with index.
You just need to tell him which parameter will it be.
E.g.:
; Component // ... cacher = action1 ; { return arrayOfFunctions; }
Now this.cacher(index, someFunction)
will return something functionally identical to:
{ ; return thispropsfunctor;}
Clearing cache
You can clear the inside cache:
{ /* do sth */}const cacher = ;const getter = cacher; const f34 = ; /* use getter */ cacherclear;const f34_prim = ;// Here ( f34 !== f34_prim )
Additional/Call/Runtime arguments
Also additional arguments can be passed.
const base = {}; { if !basecomponent basecomponent = if basecomponent return; basecomponent;} const getter = ; 'sth';'probably';'could be';'wrong';'wrong'; todeep;
More to it
You can index by any simple type:
- number
- string
- reference
Remember !
The function returned by create assumes the first argument it gets is the index, by which Cacher distinguishes cached material.
Final words
Feel free to comment and add suggestions.
This is my first lib I created and published to see how NPM works.
I am eager to enhance it if it proves useful to someone.