Guest User

Untitled

a guest
Jun 23rd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. /*
  2. generateQueryString
  3.  
  4. Returns a kebab-case js hook.
  5.  
  6. generateQueryString('fooBar')
  7. '.js-foo-bar'
  8. */
  9.  
  10. const generateQueryString = (string, prefix = 'js') =>
  11. `.${prefix}-${string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()}`
  12.  
  13. /*
  14. qs / qsa
  15.  
  16. Returns a query selector using the
  17. generateQueryString function
  18.  
  19. qs('fooBar')
  20. document.querySelector('.js-foo-bar')
  21. */
  22.  
  23. const qs = (string, prefix = 'js') =>
  24. document.querySelector(generateQueryString(string, prefix))
  25.  
  26. // Same applies, except uses querySelectorAll
  27.  
  28. const qsa = (string, prefix = 'js') =>
  29. document.querySelectorAll(generateQueryString(string, prefix))
  30.  
  31. /*
  32. qsObj / qsaObj
  33.  
  34. Returns an object containing
  35. query selectors based on provided
  36. array of strings
  37.  
  38. qsObj(['foo', 'bar', 'fooBar'])
  39. {
  40. foo: document.querySelector('.js-foo'),
  41. bar: document.querySelector('.js-bar'),
  42. fooBar: document.querySelector('.js-foo-bar')
  43. }
  44. */
  45.  
  46. const qsObj = (array, prefix = 'js') => {
  47. let object = {}
  48. array.forEach(i => {
  49. object[i] = document.querySelector(generateQueryString(i, prefix))
  50. })
  51. return object
  52. }
  53.  
  54. // Same applies, except uses querySelectorAll
  55.  
  56. const qsaObj = (array, prefix = 'js') => {
  57. let object = {}
  58. array.forEach(i => {
  59. object[i] = document.querySelectorAll(generateQueryString(i, prefix))
  60. })
  61. return object
  62. }
  63.  
  64. /*
  65. manipulateQsObj / manipulateQsaObj
  66.  
  67. Runs passed function to every element
  68. supplied in object.
  69. */
  70.  
  71. const manipulateQsObj = (object, cb) => {
  72. Object.keys(object).map(key => {
  73. cb(object[key])
  74. })
  75. }
  76.  
  77. // Same applies, except uses querySelectorAll
  78.  
  79. const manipulateQsaObj = (object, cb) => {
  80. Object.keys(object).map(key => {
  81. all(object[key], el => cb(el))
  82. })
  83. }
  84.  
  85. /*
  86. first
  87.  
  88. Returns first node in list
  89. */
  90.  
  91. const first = hook => hook[0]
  92.  
  93. /*
  94. last
  95.  
  96. Returns last node in list
  97. */
  98.  
  99. const last = hook => hook[hook.length - 1]
  100.  
  101. /*
  102. all
  103.  
  104. Runs passed function to every
  105. node in list
  106. */
  107.  
  108. const all = (hook, cb) => {
  109. ;[].forEach.call(hook, el => cb(el))
  110. }
  111.  
  112. export {
  113. qs,
  114. qsa,
  115. qsObj,
  116. qsaObj,
  117. manipulateQsObj,
  118. manipulateQsaObj,
  119. first,
  120. last,
  121. all
  122. }
Add Comment
Please, Sign In to add comment