UNPKG

800 BJavaScriptView Raw
1'use strict'
2
3const range = require('lodash.range')
4const isPlainObject = require('lodash.isplainobject')
5
6function _allPaths (object, previousPath = [], paths = []) {
7 let keys
8
9 if (isPlainObject(object)) {
10 keys = Object.keys(object)
11 } else if (Array.isArray(object)) {
12 keys = range(object.length)
13 }
14
15 if (!keys) {
16 return paths
17 }
18
19 keys.forEach(key => {
20 const pathWithKey = [].concat(previousPath).concat(key)
21 paths.push(pathWithKey)
22 _allPaths(object[key], pathWithKey, paths)
23 })
24 return paths
25}
26
27/**
28 * Given an object returns list of all possible paths in it
29 *
30 * @example allPaths({foo: {bar: 42}})
31 * // [['foo'], ['foo', 'bar']]
32 * @param {*} object Object or Array
33 */
34function allPaths (object) {
35 return _allPaths(object)
36}
37
38module.exports = allPaths