-
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.
- Loading branch information
Sean Hamilton
committed
Dec 1, 2018
1 parent
af79c62
commit 98e8d6d
Showing
1 changed file
with
61 additions
and
0 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 |
---|---|---|
@@ -0,0 +1,61 @@ | ||
// o | ||
import is from './is'; | ||
import empty from './empty'; | ||
import each from './each'; | ||
|
||
/** | ||
* Get the key of the specified value in dot notation | ||
* | ||
* @param {object} object The object to search | ||
* @param {*} value The value to look for | ||
* @param {boolean} [follow=false] Whether to follow objects | ||
* | ||
* @returns {string} The key when found else undefined | ||
*/ | ||
function keyOf(object, value, follow = false) { | ||
// if the object is an object and is not empty | ||
if (is(object) && !empty(object)) { | ||
// create a found boolean so we can skip | ||
// over keys once we have found the correct | ||
// key | ||
let found = false; | ||
// create an result variable as false | ||
let result = ''; | ||
|
||
// for each key/value in the object | ||
// follow is passed into each therefore the | ||
// each function works out whether to follow | ||
// the objects | ||
each(object, (key, objValue) => { | ||
// if the result isn't already found | ||
if (!found) { | ||
// follow is false or follow is true but the | ||
// object value isn't an object | ||
if (!follow || (follow && !is(value))) { | ||
// check if the object value is equal to | ||
// the specified value | ||
if (objValue === value) { | ||
// set found to true since the key was found | ||
found = true; | ||
|
||
// if the values are the same set the result | ||
// to the key | ||
result = key; | ||
} | ||
} | ||
} | ||
}, follow); | ||
|
||
// return the result if it was found else return | ||
// undefined | ||
return found | ||
? result | ||
: undefined; | ||
} | ||
|
||
// if the object isn't an object or is empty return | ||
// false because the object can't be checked | ||
return undefined; | ||
} | ||
|
||
export default keyOf; |