_setData.js 1.1 KB

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