setData.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var baseSetData = require('./baseSetData'),
  2. now = require('../date/now');
  3. /** Used to detect when a function becomes hot. */
  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 function
  11. * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
  12. * for more details.
  13. *
  14. * @private
  15. * @param {Function} func The function to associate metadata with.
  16. * @param {*} data The metadata.
  17. * @returns {Function} Returns `func`.
  18. */
  19. var setData = (function() {
  20. var count = 0,
  21. lastCalled = 0;
  22. return function(key, value) {
  23. var stamp = now(),
  24. remaining = HOT_SPAN - (stamp - lastCalled);
  25. lastCalled = stamp;
  26. if (remaining > 0) {
  27. if (++count >= HOT_COUNT) {
  28. return key;
  29. }
  30. } else {
  31. count = 0;
  32. }
  33. return baseSetData(key, value);
  34. };
  35. }());
  36. module.exports = setData;