All files / utils traverse.ts

100% Statements 10/10
87.5% Branches 7/8
100% Functions 3/3
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                              30x 5x 10x 10x 10x     25x 8x 13x 13x 9x          
import { forOwn, has, isPlainObject } from 'lodash-uni'
 
/**
 * 遍历对象和数组。
 *
 * @param value 要遍历的值
 * @param callback 遍历回调
 * @returns 返回结果
 * @example
 * ```typescript
 * traverse([1, 2, {3: 4}], value => {
 *   console.log(value)
 *   // => 1
 *   // => 2
 *   // => {3: 4}
 *   // => 4
 * })
 * ```
 */
export function traverse(
  value: any,
  callback: (value: any, key: string | number, parent: any) => any,
): void {
  if (Array.isArray(value)) {
    value.forEach((item, index) => {
      callback(item, index, value)
      if (value[index] !== undefined) {
        traverse(item, callback)
      }
    })
  } else if (isPlainObject(value)) {
    forOwn(value, (item, key) => {
      callback(item, key, value)
      if (has(value, key)) {
        traverse(item, callback)
      }
    })
  }
}