-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
40 lines (31 loc) · 1.02 KB
/
index.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
'use strict';
const isObject = value => value !== null && typeof value === 'object';
const traversePrimitive = function (object, target, options) {
for (const [key, value] of Object.entries(object)) {
if (key === target || value === target) {
return true;
}
if (options.deep && typeof value === 'object') {
return traversePrimitive(value, target, options);
}
}
return false;
};
const traverseObject = function (object, target, options) {
for (const [, value] of Object.entries(object)) {
if (JSON.stringify(value) === target) {
return true;
}
if (options.deep && typeof value === 'object') {
return traverseObject(value, target, options);
}
}
return false;
};
module.exports = (object, target, options) => {
if (!isObject(object)) {
throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`);
}
options = {deep: false, ...options};
return typeof target === 'object' ? traverseObject(object, JSON.stringify(target), options) : traversePrimitive(object, target, options);
};