-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #16 from collective/get_items_by_path
refactor: get items by path
- Loading branch information
Showing
3 changed files
with
26 additions
and
12 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
export function getItemsByPath(items, pathname) { | ||
let rootPathConfig = null; | ||
const itemsByPath = items?.reduce((acc, val) => { | ||
if (val.rootPath === '/') { | ||
rootPathConfig = val; | ||
return acc; | ||
} | ||
return { ...acc, [val.rootPath]: val }; | ||
}, {}); | ||
const matchingPaths = Object.keys(itemsByPath) | ||
.filter((path) => pathname.startsWith(path)) | ||
.sort((a, b) => { | ||
return a.length < b.length; | ||
}); | ||
|
||
if (matchingPaths.length > 0) return itemsByPath[matchingPaths[0]].items; | ||
else if (rootPathConfig) return rootPathConfig.items; | ||
else return []; | ||
} |