Skip to content

Commit

Permalink
feat(each): add each function
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Hamilton committed Nov 30, 2018
1 parent deed825 commit 648faf7
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/each.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// o
import is from './is';
import empty from './empty';
import flattenKeys from './flattenKeys';

/**
* Foreach over the object
*
* @param {object} object The object to iterate over
* @param {function(key: string, value: *)} iterator The iterator function
* @param {boolean} [follow=false] Whether to follow objects
*/
function each(object, iterator, follow = false) {
// check if the object is an object and isn't empty
// if it is it would be pointless running the forEach
if (is(object) && !empty(object)) {
// if follow is true flatten the object keys so
// its easy to get the path and values if follow
// is false it will just be the base object
// therefore it will only use the base keys
const flattenedObject = follow
? flattenKeys(object)
: object;

// loop over the keys of the object
Object.keys(flattenedObject).forEach((key) => {
// get the value of the current key
const value = flattenedObject[key];

// check if the iterator is a function
if (typeof iterator === 'function') {
// if it is run the iterator with the
// key and value
iterator(key, value);
}
});
}
}

export default each;

0 comments on commit 648faf7

Please # to comment.