Skip to content

Instantly share code, notes, and snippets.

@okumurakengo
Created May 8, 2020 09:06
Show Gist options
  • Save okumurakengo/b12bdf16cac76c1d6f07d182e198aa03 to your computer and use it in GitHub Desktop.
Save okumurakengo/b12bdf16cac76c1d6f07d182e198aa03 to your computer and use it in GitHub Desktop.
フォルダ階層たどってJSONにしてくれるの
module.exports = `
foo.html
bar/hoge/fuga.php
bar/hoge/piyo.php
bar/hogera.php
baz/fugara.php
`
const files = require("./files")
const res = files
.split("\n")
.filter(v => v !== "")
.map(path => path.split("/"))
.reduce((acc, filepath) => {
const last = filepath.pop()
const fn = (acc, arr, last) => {
if (arr.length === 0) {
acc.push(last)
return
}
const key = arr.shift()
const find = acc.find(obj =>
typeof obj === "object"
&& key in obj)
const crrent = { [key]: [] }
if (!find) {
acc.push(crrent)
}
fn(find ? find[key] : crrent[key], arr, last)
}
fn(acc, filepath, last)
return acc
}, [])
console.log(JSON.stringify(res, null, ' '))
// [
// "foo.html",
// {
// "bar": [
// {
// "hoge": [
// "fuga.php",
// "piyo.php"
// ]
// },
// "hogera.php"
// ]
// },
// {
// "baz": [
// "fugara.php"
// ]
// }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment