Last active
September 2, 2020 21:21
-
-
Save crazy4groovy/fd32470bffcd593b9ba3347db3ca204e to your computer and use it in GitHub Desktop.
Given an array of Directories/Filenames, find the longest filename
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
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