Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Iterates over the given array values to find an element which matches the given needle.
- *
- * @param haystack The array to iterate over
- * @param needle The pattern to look for
- * @return {boolean} true if a matching element was found, false otherwise.
- */
- const arrayIncludesRegEx = (haystack, needle) => {
- // Validate input parameters
- if (typeof haystack !== 'object' || typeof haystack.length !== 'number') {
- throw new TypeError('Expected parameter haystack to be an Array');
- } else if (typeof needle !== 'object' || typeof needle.test !== 'function') {
- throw new TypeError('Expected parameter needle to be an regular expression');
- } else {
- // Iterate over array to find an element which matches the given needle
- const index = haystack.findIndex((element) => {
- return needle.test(element);
- });
- // Return index is not lesser than 0 which means, that a matching value was found
- return index > -1;
- }
- };
- // Example usage:
- const arr = [ 'apple', 'orange', 'banana' ];
- arrayIncludesRegEx(arr, /(pea)/i); // return false
- arrayIncludesRegEx(arr, /(nana)/i); // return true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement