-
Notifications
You must be signed in to change notification settings - Fork 1
/
is-match.js
64 lines (57 loc) · 1.44 KB
/
is-match.js
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
57
58
59
60
61
62
63
64
const byValue = ({ shouldBe, value, not }) =>
not ? shouldBe !== value : shouldBe === value
const byFn = ({ shouldBe, value, not }) => {
const result = shouldBe(value) === true
return not ? !result : result
}
/**
* Determines if one object's properties are equal to another
*
* @tag Core
* @signature (subset: Object)(source: Object): boolean
*
* @param {Object} subset Set of properties that should match
* @param {Object} source Object matching against
*
* @return {boolean} True if all "subset" properties are of equal (shallow
* compare) value to properties in "source" object,
* otherwise false
*
* @example
*
* isMatch({
* id: 2,
* parentId: null,
* })({
* id: 2,
* parentId: null
* name: "John",
* })
* // true
*
* isMatch({
* "!parentId": null,
* "name": "John",
* })({
* id: 2,
* parentId: null,
* name: "John",
* })
* // false
*/
module.exports = subset => source => {
const subsetEntries = Object.entries(subset)
for (let i = 0, length = subsetEntries.length; i < length; i++) {
const [key, shouldBe] = subsetEntries[i]
const not = key[0] === "!"
const cleanKey = key.replace("!", "")
const isFieldMatch =
typeof shouldBe === "function"
? byFn({ shouldBe, value: source[cleanKey], not })
: byValue({ shouldBe, value: source[cleanKey], not })
if (isFieldMatch === false) {
return false
}
}
return true
}