Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active September 2, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/fd32470bffcd593b9ba3347db3ca204e to your computer and use it in GitHub Desktop.
Save crazy4groovy/fd32470bffcd593b9ba3347db3ca204e to your computer and use it in GitHub Desktop.
Given an array of Directories/Filenames, find the longest filename
function processDir(d, par = '') {
let dirnm = par
return d.map(item => {
if (Array.isArray(item)) { // this is a folder
return processDir(item, dirnm)
}
dirnm = par + '/' + item
if (item.indexOf('.') > -1) { // this is a filename
return dirnm
}
// return undefined
})
.filter(z => !!z) // remove dead-end folders
.flat()
}
function findLongestStr(arr) {
// return arr.slice().sort((a,b) => a.length - b.length).pop()
const max = Math.max(...(arr.map(x => x.length)))
const i = arr.findIndex(x => x.length === max)
return arr[i]
}
let dirs = ["dir", ["sub1", ["file1.ext", "sub22222222222222222222222!"], "sub3", ["sub4", ["file2.ext"]]]]
// "/dir/sub3/sub4/file2.ext"
findLongestStr(processDir(dirs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment