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