Skip to content

Instantly share code, notes, and snippets.

@sebbdk
Last active February 19, 2020 09:37
Show Gist options
  • Save sebbdk/a89f9638c690f63c0cb8765cb1bc29ca to your computer and use it in GitHub Desktop.
Save sebbdk/a89f9638c690f63c0cb8765cb1bc29ca to your computer and use it in GitHub Desktop.
Tree search, throw vs array vs null
// 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