Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. /**
  2. * Iterates over the given array values to find an element which matches the given needle.
  3. *
  4. * @param haystack The array to iterate over
  5. * @param needle The pattern to look for
  6. * @return {boolean} true if a matching element was found, false otherwise.
  7. */
  8. const arrayIncludesRegEx = (haystack, needle) => {
  9. // Validate input parameters
  10. if (typeof haystack !== 'object' || typeof haystack.length !== 'number') {
  11. throw new TypeError('Expected parameter haystack to be an Array');
  12. } else if (typeof needle !== 'object' || typeof needle.test !== 'function') {
  13. throw new TypeError('Expected parameter needle to be an regular expression');
  14. } else {
  15. // Iterate over array to find an element which matches the given needle
  16. const index = haystack.findIndex((element) => {
  17. return needle.test(element);
  18. });
  19.  
  20. // Return index is not lesser than 0 which means, that a matching value was found
  21. return index > -1;
  22. }
  23. };
  24.  
  25. // Example usage:
  26. const arr = [ 'apple', 'orange', 'banana' ];
  27.  
  28. arrayIncludesRegEx(arr, /(pea)/i); // return false
  29. arrayIncludesRegEx(arr, /(nana)/i); // return true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement