-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathdecko.js
107 lines (97 loc) · 2.53 KB
/
decko.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const EMPTY = {};
const HOP = Object.prototype.hasOwnProperty;
let fns = {
/** let cachedFn = memoize(originalFn); */
memoize(fn, opt=EMPTY) {
let cache = opt.cache || {};
return function(...a) {
let k = String(a[0]);
if (opt.caseSensitive===false) k = k.toLowerCase();
return HOP.call(cache,k) ? cache[k] : (cache[k] = fn.apply(this, a));
};
},
/** let throttled = debounce(10, console.log); */
debounce(fn, opts) {
if (typeof opts==='function') { let p = fn; fn = opts; opts = p; }
let delay = opts && opts.delay || opts || 0,
args, context, timer;
return function(...a) {
args = a;
context = this;
if (!timer) timer = setTimeout( () => {
fn.apply(context, args);
args = context = timer = null;
}, delay);
};
},
bind(target, key, { value: fn }) {
// In IE11 calling Object.defineProperty has a side-effect of evaluating the
// getter for the property which is being replaced. This causes infinite
// recursion and an "Out of stack space" error.
let definingProperty = false;
return {
configurable: true,
get() {
if (definingProperty) {
return fn;
}
let value = fn.bind(this);
definingProperty = true;
Object.defineProperty(this, key, {
value,
configurable: true,
writable: true
});
definingProperty = false;
return value;
}
};
}
};
let memoize = multiMethod(fns.memoize),
debounce = multiMethod(fns.debounce),
bind = multiMethod((f,c)=>f.bind(c), ()=>fns.bind);
export { memoize, debounce, bind };
export default { memoize, debounce, bind };
/** Creates a function that supports the following calling styles:
* d() - returns an unconfigured decorator
* d(opts) - returns a configured decorator
* d(fn, opts) - returns a decorated proxy to `fn`
* d(target, key, desc) - the decorator itself
*
* @Example:
* // simple identity deco:
* let d = multiMethod( fn => fn );
*
* class Foo {
* @d
* bar() { }
*
* @d()
* baz() { }
*
* @d({ opts })
* bat() { }
*
* bap = d(() => {})
* }
*/
function multiMethod(inner, deco) {
deco = deco || inner.decorate || decorator(inner);
let d = deco();
return (...args) => {
let l = args.length;
return (l<2 ? deco : (l>2 ? d : inner))(...args);
};
}
/** Returns function supports the forms:
* deco(target, key, desc) -> decorate a method
* deco(Fn) -> call the decorator proxy on a function
*/
function decorator(fn) {
return opt => (
typeof opt==='function' ? fn(opt) : (target, key, desc) => {
desc.value = fn(desc.value, opt, target, key, desc);
}
);
}