deepMatches.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var forOwn = require('./forOwn');
  2. var isArray = require('../lang/isArray');
  3. function containsMatch(array, pattern) {
  4. var i = -1, length = array.length;
  5. while (++i < length) {
  6. if (deepMatches(array[i], pattern)) {
  7. return true;
  8. }
  9. }
  10. return false;
  11. }
  12. function matchArray(target, pattern) {
  13. var i = -1, patternLength = pattern.length;
  14. while (++i < patternLength) {
  15. if (!containsMatch(target, pattern[i])) {
  16. return false;
  17. }
  18. }
  19. return true;
  20. }
  21. function matchObject(target, pattern) {
  22. var result = true;
  23. forOwn(pattern, function(val, key) {
  24. if (!deepMatches(target[key], val)) {
  25. // Return false to break out of forOwn early
  26. return (result = false);
  27. }
  28. });
  29. return result;
  30. }
  31. /**
  32. * Recursively check if the objects match.
  33. */
  34. function deepMatches(target, pattern){
  35. if (target && typeof target === 'object') {
  36. if (isArray(target) && isArray(pattern)) {
  37. return matchArray(target, pattern);
  38. } else {
  39. return matchObject(target, pattern);
  40. }
  41. } else {
  42. return target === pattern;
  43. }
  44. }
  45. module.exports = deepMatches;