You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
941 B

4 years ago
  1. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  2. var HOT_COUNT = 800,
  3. HOT_SPAN = 16;
  4. /* Built-in method references for those with the same name as other `lodash` methods. */
  5. var nativeNow = Date.now;
  6. /**
  7. * Creates a function that'll short out and invoke `identity` instead
  8. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  9. * milliseconds.
  10. *
  11. * @private
  12. * @param {Function} func The function to restrict.
  13. * @returns {Function} Returns the new shortable function.
  14. */
  15. function shortOut(func) {
  16. var count = 0,
  17. lastCalled = 0;
  18. return function() {
  19. var stamp = nativeNow(),
  20. remaining = HOT_SPAN - (stamp - lastCalled);
  21. lastCalled = stamp;
  22. if (remaining > 0) {
  23. if (++count >= HOT_COUNT) {
  24. return arguments[0];
  25. }
  26. } else {
  27. count = 0;
  28. }
  29. return func.apply(undefined, arguments);
  30. };
  31. }
  32. module.exports = shortOut;