Skip to content

Instantly share code, notes, and snippets.

@JeremieLitzler
Created April 4, 2018 04:02
Show Gist options
  • Save JeremieLitzler/a40567879d93a0e103ec3a5303f471d6 to your computer and use it in GitHub Desktop.
Save JeremieLitzler/a40567879d93a0e103ec3a5303f471d6 to your computer and use it in GitHub Desktop.
Recursive path array
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