-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
performance improved by refactoring checks into different functions
- Loading branch information
Muhammad Faizan Uddin
committed
Mar 8, 2021
1 parent
280efae
commit 58d0ca8
Showing
1 changed file
with
21 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,40 @@ | ||
'use strict'; | ||
|
||
const isObject = value => typeof value === 'object' && value !== null; | ||
const isObject = value => value !== null && typeof value === 'object'; | ||
|
||
const traverse = function (object, target, options) { | ||
const traversePrimitive = function (object, target, options) { | ||
for (const [key, value] of Object.entries(object)) { | ||
if (key === target || (typeof value === 'object' ? JSON.stringify(value) === target : value === target)) { | ||
options.exists = true; | ||
if (key === target || value === target) { | ||
return true; | ||
} | ||
|
||
if (options.deep && typeof value === 'object') { | ||
traverse(value, target, options); | ||
return traversePrimitive(value, target, options); | ||
} | ||
} | ||
|
||
return options.exists; | ||
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, exists: false, ...options}; | ||
return traverse(object, typeof target === 'object' ? JSON.stringify(target) : target, options); | ||
options = {deep: false, ...options}; | ||
return typeof target === 'object' ? traverseObject(object, JSON.stringify(target), options) : traversePrimitive(object, target, options); | ||
}; |