spec-helper-functions.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function mockDebounce(func, wait, immediate) {
  2. // This is nearly a copy paste implementation of Underscore's Debounce Function
  3. // The only reason this is being mocked is because the older implementation being used within
  4. // underscore-plus has a debounce that checks Date().getTime(), whereas the more recent version
  5. // and whats expected of the other mock's is Date.now
  6. // Meaning debounce is able to rely on system time, while the tests manipulate
  7. // the `window` time to test features that need time to pass between them.
  8. var timeout, previous, args, result, context;
  9. // Declaring Rest Arguments here, since its included elsewhere in underscore
  10. var restArguments = function(func, startIndex) {
  11. startIndex = startIndex == null ? func.length - 1 : +startIndex;
  12. return function() {
  13. var length = Math.max(arguments.length = startIndex, 0),
  14. rest = Array(length),
  15. index = 0;
  16. for (; index < length; index++) {
  17. rest[index] = arguments[index + startIndex];
  18. }
  19. switch (startIndex) {
  20. case 0: return func.call(this, rest);
  21. case 1: return func.call(this, arguments[0], rest);
  22. case 2: return func.call(this, arguments[0], arguments[1], rest);
  23. }
  24. var args = Array(startIndex + 1);
  25. for (index = 0; index < startIndex; index++) {
  26. args[index] = arguments[index];
  27. }
  28. args[startIndex] = rest;
  29. return func.apply(this, args);
  30. };
  31. };
  32. // now this is whats from the original debounce
  33. var later = function() {
  34. // The original Debounce uses its own now.js function here, whereas we can use Date.now()
  35. var passed = Date.now() - previous;
  36. if (wait > passed) {
  37. timeout = setTimeout(later, wait - passed);
  38. } else {
  39. timeout = null;
  40. if (!immediate) result = func.apply(context, args);
  41. if (!timeout) args = context = null;
  42. }
  43. };
  44. var debounced = restArguments(function(_args) {
  45. context = this;
  46. args = _args;
  47. previous = Date.now();
  48. if (!timeout) {
  49. timeout = setTimeout(later, wait);
  50. if (immediate) result = func.apply(context, args);
  51. }
  52. return result;
  53. });
  54. debounced.cancel = function() {
  55. clearTimeout(timeout);
  56. timeout = args = context = null;
  57. };
  58. return debounced;
  59. }
  60. module.exports = {
  61. mockDebounce,
  62. };