UNPKG

1.09 kBJavaScriptView Raw
1import baseSetData from './_baseSetData';
2import now from './now';
3
4/** Used to detect hot functions by number of calls within a span of milliseconds. */
5var HOT_COUNT = 150,
6 HOT_SPAN = 16;
7
8/**
9 * Sets metadata for `func`.
10 *
11 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
12 * period of time, it will trip its breaker and transition to an identity
13 * function to avoid garbage collection pauses in V8. See
14 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
15 * for more details.
16 *
17 * @private
18 * @param {Function} func The function to associate metadata with.
19 * @param {*} data The metadata.
20 * @returns {Function} Returns `func`.
21 */
22var setData = (function() {
23 var count = 0,
24 lastCalled = 0;
25
26 return function(key, value) {
27 var stamp = now(),
28 remaining = HOT_SPAN - (stamp - lastCalled);
29
30 lastCalled = stamp;
31 if (remaining > 0) {
32 if (++count >= HOT_COUNT) {
33 return key;
34 }
35 } else {
36 count = 0;
37 }
38 return baseSetData(key, value);
39 };
40}());
41
42export default setData;