Guest User

Untitled

a guest
Dec 14th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. export function debounce(func: Function, wait?: number, immediate?: boolean) {
  2. let timeout: any
  3.  
  4. return function() {
  5. const context = null
  6. const args = arguments
  7. const later = function() {
  8. timeout = null
  9. if (!immediate) func.apply(context, args)
  10. }
  11. const callNow = immediate && !timeout
  12. clearTimeout(timeout)
  13. timeout = setTimeout(later, wait)
  14. if (callNow) func.apply(context, args)
  15. }
  16. }
  17.  
  18. interface ThrottleParams {
  19. leading?: boolean
  20. trailing?: boolean
  21. }
  22.  
  23. export function throttle(
  24. func: Function,
  25. wait: number,
  26. options: ThrottleParams = { leading: true, trailing: true }
  27. ): () => void {
  28. const context = null
  29. // handle case when an empty object is passed
  30. if (!Object.keys(options).length) {
  31. options = {
  32. leading: true,
  33. trailing: true
  34. }
  35. }
  36. let args: IArguments | null
  37. let result: any
  38. let timeout: any = null
  39. let previous = 0
  40.  
  41. const later = function() {
  42. previous = options.leading === false ? 0 : Date.now()
  43. timeout = null
  44. result = func.apply(context, args)
  45. if (!timeout) args = null
  46. }
  47.  
  48. return function() {
  49. const now = Date.now()
  50. if (!previous && options.leading === false) previous = now
  51. const remaining = wait - (now - previous)
  52. args = arguments
  53. if (remaining <= 0 || remaining > wait) {
  54. if (timeout) {
  55. clearTimeout(timeout)
  56. timeout = null
  57. }
  58. previous = now
  59. result = func.apply(context, args)
  60. if (!timeout) args = null
  61. } else if (!timeout && options.trailing !== false) {
  62. timeout = setTimeout(later, remaining)
  63. }
  64.  
  65. return result
  66. }
  67. }
  68.  
  69. export function isMultipleOf(nth: number) {
  70. return (num: number) => num % nth === 0
  71. }
  72.  
  73. export function everyNth<T>(arr: T[], nth: number, startFromHead?: boolean): T[] {
  74. return arr.filter((_item, i) => {
  75. const isHead = i === 0
  76. return (startFromHead && isHead) ||
  77. i % nth === nth - (startFromHead ? nth : 1)
  78. })
  79. }
Add Comment
Please, Sign In to add comment