File: index.js

package info (click to toggle)
node-deep-for-each 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 572 kB
  • sloc: javascript: 742; makefile: 5
file content (35 lines) | stat: -rw-r--r-- 921 bytes parent folder | download | duplicates (2)
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
import isPlainObject from 'lodash.isplainobject';

function forEachObject(obj, fn, path) {
    for (const key in obj) {
        const deepPath = path ? `${path}.${key}` : key;

        // Note that we always use obj[key] because it might be mutated by forEach
        fn.call(obj, obj[key], key, obj, deepPath);

        forEach(obj[key], fn, deepPath);
    }
}

function forEachArray(array, fn, path) {
    array.forEach((value, index, arr) => {
        const deepPath = `${path}[${index}]`;

        fn.call(arr, value, index, arr, deepPath);

        // Note that we use arr[index] because it might be mutated by forEach
        forEach(arr[index], fn, deepPath);
    });
}

function forEach(value, fn, path) {
    path = path || '';

    if (Array.isArray(value)) {
        forEachArray(value, fn, path);
    } else if (isPlainObject(value)) {
        forEachObject(value, fn, path);
    }
}

export default forEach;