You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A concise implementation of the three most useful decorators:
@bind: make the value of this constant within a method
@debounce: throttle calls to a method
@memoize: cache return values based on arguments
Decorators help simplify code by replacing the noise of common patterns with declarative annotations.
Conversely, decorators can also be overused and create obscurity.
Decko establishes 3 standard decorators that are immediately recognizable, so you can avoid creating decorators in your own codebase.
Each decorator method is available as a named import.
import{bind,memoize,debounce}from'decko';
@bind
classExample{
@bindfoo(){// the value of `this` is always the object from which foo() was referenced.returnthis;}}lete=newExample();assert.equal(e.foo.call(null),e);
@memoize
Cache values returned from the decorated function.
Uses the first argument as a cache key.
Cache keys are always converted to strings.
Options:
caseSensitive: false - Makes cache keys case-insensitive
cache: {} - Presupply cache storage, for seeding or sharing entries
classExample{
@memoizeexpensive(key){letstart=Date.now();while(Date.now()-start<500)key++;returnkey;}}lete=newExample();// this takes 500msletone=e.expensive(1);// this takes 0mslettwo=e.expensive(1);// this takes 500msletthree=e.expensive(2);
@debounce
Throttle calls to the decorated function. To debounce means "call this at most once per N ms".
All outward function calls get collated into a single inward call, and only the latest (most recent) arguments as passed on to the debounced function.
Options:
delay: 0 - The number of milliseconds to buffer calls for.
classExample{
@debouncefoo(){returnthis;}}lete=newExample();// this will only call foo() once:for(leti=1000;i--)e.foo();
License
MIT
About
💨 The 3 most useful ES7 decorators: bind, debounce and memoize