Last active
February 19, 2020 09:37
-
-
Save sebbdk/a89f9638c690f63c0cb8765cb1bc29ca to your computer and use it in GitHub Desktop.
Tree search, throw vs array vs null
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
// Con, un-used catch, performance?, un-used catch is a codesmell | |
function findPage(pid, pages:IPage[]): IPage { | |
for(const page of pages) { | |
if (page.pageId === pid) return page; | |
if(page.subPages.length > 0) { | |
try { | |
return findPage(pid, page.subPages); | |
} catch {} | |
} | |
} | |
throw(`${pid} not found`); | |
} | |
// Con, not the desired return type, nullcheck with extra steps? | |
function findPage2(pid, pages:IPage[]): IPage[] { | |
for(const page of pages) { | |
if (page.pageId === pid) return [page]; | |
if(page.subPages.length > 0) { | |
const sp = findPage2(pid, page.subPages); | |
if (sp.length > 0) return sp; | |
} | |
} | |
return [] | |
} | |
// Con, changed return type, NullExceptions likely | |
function findPageNull(pid, pages:IPage[]): IPage[] { | |
for(const page of pages) { | |
if (page.pageId === pid) return [page]; | |
if(page.subPages.length > 0) { | |
const sp = findPageNull(pid, page.subPages); | |
if (sp !== null) return sp; | |
} | |
} | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment