Created
April 4, 2018 04:02
-
-
Save JeremieLitzler/a40567879d93a0e103ec3a5303f471d6 to your computer and use it in GitHub Desktop.
Recursive path array
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
const locations = { | |
usa: { | |
alaska: ["Fairbanks", "Wasilla"], | |
california: ["San Fransisco", "Los Angeles"], | |
nevada: ["Las Vegas"], | |
massachusetts: ["Charlton"], | |
washington: ["Seattle"], | |
} | |
} | |
// helper function to make finding type cleaner | |
function is(item, type) { | |
const objectType = Object.prototype.toString.call(item) | |
return objectType.toLowerCase() === `[object ${type.toLowerCase()}]` | |
} | |
function getPaths(iterable, result=[], tempPath=[]) { | |
if (!is(iterable, 'object') && !is(iterable, 'array')) { | |
result.push(tempPath.join('/').toUpperCase()) | |
} | |
if (is(iterable, 'object')) { | |
Object.keys(iterable).map(item => { | |
const curPath = [...tempPath] | |
curPath.push(item) | |
getPaths(iterable[item], result, curPath) | |
}) | |
} | |
if (is(iterable, 'array')) { | |
iterable.map(item => { | |
const curPath = [...tempPath] | |
curPath.push(item) | |
getPaths(iterable[item], result, curPath) | |
}) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment